I was wondering if any of you know any best practices 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 advice here would be 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 any way around this ugly manual logging, or am I stuck with it?
logging
, operations actually either want an audit trail or event sourcing. Logs are not reliable: You logged"Something done on bar with id=..."
, but what if changes todbContext
never saved? \$\endgroup\$