Context
Next up is context. A few articles out there talk about context and how it can make all the difference when using a log to diagnose problems but I don’t think they go into enough detail. Now logging is all about reading the log to find out what happened so the correct context for a particular entry is going to be specific to the problem that you’re diagnosing which of course you won’t know at the time of writing the code. For this reason frameworks give you several ways of providing common and specific contexts.
Contexts include the following:
- Time
- Application run
- Importance
- Location
- Thread
- Custom contexts used as correlation IDs
These common contexts you basically get for free if you follow the patterns recommended by the framework.
Time
The time that the logging was performed. This is the most basic of contexts and you don’t need to do anything to include this in the output. Simply calling a logging method will pin the time to the entry and it can be printed using the “%date” conversion pattern variable.
Application Run
Which application run your code is in i.e. has the application been restarted since the previous log entry. It might seem obvious but if you’re analysing a log weeks after the event and its the only thing you’ve got then it’s probably going to be good to know if the application was restarted. Assuming you don’t have any other log entries concerning the start-up portion of the application then you can add them purely through configuration.
<layout type="log4net.Layout.PatternLayout">
<header value=" [Application Started] " />
<footer value="[Application Stopped] " />
<conversionPattern value="%date %-5level %message%newline" />
</layout>Do note that the header and footer patterns don’t support variable substitution though including new lines so you need to use html notation.
Location
The location of the code that performed the logging. As long as your code is well written then a granularity of class level is often enough detail for this and to ensure that the class can be included in the log output log4net recomends that you have one logger per class. Now this may sound a little overkill but its probably all in the terminology. log4net and many other frameworks provide seperation between the source of the log entries and their destination. The sources are called ‘loggers’ and are the things that you’ll instantiate in code and write log entries to. The destinations are called ‘appenders’, such as an appender to write to a file or to a database and are usually defined in configuration.
Thread
The thread that performed the logging. The “%thread” conversion pattern vaiable can be used to print the thread name (or number if it has no name).