Skip to main content
2 of 5
rm thanks
svick
  • 24.5k
  • 4
  • 53
  • 89

Logging without Code Bloat

I was wondering if any of you new any best practises or design patterns so that I can have good logging in my programs without them looking messy or bloated.

I am currently using C# and NLog however I guess any advise here language and tool agnostic.

The problem we have is that we want to have good logging, however we can't seem to find a way around having many lines which just log operations, which can turn a simple method like this:

void Foo() { Bar bar = dbContext().Bars.First(); bool someCondition = bar.DoSomething(); if (someContition) { dbContext().FooBars.Add(new FooBar()); } } 

Into something which looks like this:

void Foo() { _logger.Info("Getting first bar from database..."); Bar bar = dbContext().Bars.First(); _logger.Info("First bar returned from database, id = {0}", bar.Id); _logger.Info("Doing something on bar with id = {0}", bar.Id); bool someCondition = bar.DoSomething(); _logger.Info("Something done on bar with id = {0}, response = {1}", bar.Id, someCondition); if (someContition) { _logger.Warn("Adding new FooBar to database"); dbContext().FooBars.Add(new FooBar()); _logger.Warn("Added new FooBar to database successfully"); } } 

Here we now have more logging lines than code lines.

However I am being told by operations that this level of logging is required, and at the moment is still too coarse.

Is there anyway around this ugly manual logging, or am I stuck with it?

Pete Petersen
  • 783
  • 2
  • 6
  • 11