使用log4net在日志消息中处理嵌入换行符
问题描述:
当日志消息包含嵌入的新行字符时,日志文件中这些日志消息的对齐方式不正确。使用log4net在日志消息中处理嵌入换行符
例如,如果我使用的变换图案: [%-5level]%消息%的换行符
,如果我记录异常堆栈跟踪它包含嵌入的新行字符,或任何其它多行日志消息,则消息中的附加行从行的开始处开始。
对于每个这样的附加行,是否可能遵循转换模式,并且文本是否适当缩进?
答
我做了以下方法:
void Log(string message, int levelsDeep)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < levelsDeep; i++)
sb.Append(" ");
string spacer = sb.ToString();
string msg = message.Replace("\r\n", "\r\n" + spacer);
msg = "\r\n" + msg + "\r\n"; //the prefix and suffix newline characters ensure that this and the next message starts in a new line and is not impacted by the 'spacer' from this message.
// call log4net functions to log the 'msg'
}