我正在进行生产支持,很大程度上依赖日志来进行故障排查。我发现目前的日志信息非常混乱。
你能提供编写日志信息的最佳实践或指南吗?
顺便说一下:我们正在使用log4Net。你有关于替代库的建议吗?
谢谢。
我赞同@Oded提供的保持消息整洁的建议。对于例行工作,如日期和时间、日志级别、错误代码,我会尝试将它们格式化为固定宽度,并将它们放在开头。这使得扫描日志变得更加容易。
关于日志消息格式的良好指南,我遇到的唯一一件事是《发布它!》第17章:http://www.pragprog.com/titles/mnee/release-it 上述大部分建议都基于此书。
//Context value names
public static class DiagnosticContextValueNames
{
public static string TransactionId = "transactionid";
public static string SessionId = "sessionid";
}
//In your code
log4net.ThreadContext.Properties[DiagnosticContextValueNames.TransactionId] = GetTransactionId();
log4net.ThreadContext.Properties[DiagnosticContextValueNames.SessionId] = GetSessionId();
//Somewhere later on...
logger.Info("hello"); // this message can be tagged with the transaction id and session id if you use the appropriate formatting options
public static class LoggingExtensions
{
public static void SetTransactionId(this ThreadContextProperties props, string trans)
{
props["TransactionId"] = trans;
// Or, using constants as defined above...
props[ThreadContextValueNames.TransactionId] = trans;
}
}
// In your code...
log4net.ThreadContext.Properties.SetTransactionId(GetTransactionId());
// As compared to this:
log4net.ThreadContext.Properties["transactionid"] = GetTransactionId();
// This approach requires more effort than simply populating the context properties "normally", and
// is probably overkill for most situations. However, it can prove useful if you are able
// to have access to the context information that you want to log from within the Log method
// of the logger.
public void Log(type loggerBoundaryDeclaringType, LogLevel level, object message, object exception)
{
log4net.ThreadContext.Properties["transactionid"] = GetTransactionId();
log4net.ThreadContext.Properties["sessionid"] = GetSessionId();
_logger.Log(loggerBoundaryDeclaringType, level, message, exception);
}
ELMAH 是一个非常好的日志记录库,也是log4net不错的替代品。
关于日志格式(您说信息“混乱”,但没有解释具体意思) - 确保每个条目与其他条目清晰分开,并以可读的方式格式化(间距、换行等...)。
> ... we're using log4Net. Do you have any suggestion on alternative library?
你可以使用 common.logging(http://netcommon.sourceforge.net),它是一个与以下日志记录器一起使用的小型日志记录包装器:
这使得日志记录配置变得更加复杂,因为您必须配置要使用的日志记录引擎,并且还必须配置日志记录引擎。
其日志记录 API 受 log4net-api 启发。