Some developers consider logging to be a thief of performance and a false hope when they need to locate a bug. I consider it to be helpful in debugging scenarios and only experienced performance issues because of logging when it was used unwise. One way to make logs to be more helpful is to include a session ID in server-side log entries. Here is how to do it.

Your session ID might be the session ID of the http session, the session ID of the database session, or a custom-made session ID. It has to be informative, that’s all. In the following code snippet I chose NHibernate’s session ID:

ISession session = _sessionFactory.OpenSession();
ITransaction transaction = session.BeginTransaction();

if (session is SessionImpl sessionImpl)
{
    Guid sessionId = sessionImpl.SessionId;
    // transfer the session ID to the logging subsystem
// ...
}

To include the complete GUID in each log entry is perhaps a bit too much. In most cases a sub-string of it is unambiguous enough. So, let’s reduce it to the first six characters (four would also do):

string sessionIdForLogging = sessionId.ToString().Substring(0, 6);

The following code snippet shows how we can use a thread local variable to make the session ID accessible for log4net, which is my favorite logging library:

LogicalThreadContext.Properties["SessionId"] = sessionIdForLogging;

So far log4net does not sense that there is some property to include in log entries. The property tag in the pattern does the job:

%date [%2thread] %-5level %property{SessionId} %logger{1} - %message%newline

If you want your logs to be helpful, you still need to invest a little time into it. As with unit tests logging can be implemented quite easily while the system grows. If you try to implement it in a grown system, it is costly. I hope this little article helps you to get more out of your log files.

About me

Jack of all trades, husband, father, software engineer.