NLog:如何控制LogEventInfo对象中消息的格式? [英] NLog: How do I control the format of a message from a LogEventInfo object?
问题描述
我是NLog的新手,并且一直在使用LogEventInfo对象,因为我认为我的应用程序中将需要它们.我创建了一个带有纯文本字符串的LogEventInfo对象,然后使用设置为写入$ {message}的FileAppender调用Logger.Debug(myEventInfoObject).在我希望看到我的文本字符串的地方,我看到的是记录器名称,消息级别,消息和序列ID.我发现那个扩展的字符串是我调用myEventInfoObject.ToString()时得到的.当$ {message}来自LogEventInfo对象时,如何控制显示的内容?
I'm new to NLog, and I've been playing with LogEventInfo objects, since I think I'll need them in my application. I created a LogEventInfo object with a plain text string, and then I called Logger.Debug(myEventInfoObject), using a FileAppender set up to write ${message}. Where I expected to see my text string, I saw instead the logger name, the message level, the message, and the sequence ID. I found that that expanded string is what I get when I call myEventInfoObject.ToString(). How can I control what appears when ${message} comes from a LogEventInfo object?
这是我的配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
throwExceptions="true">
<targets>
<target name="file" xsi:type="File" layout="${longdate} ${logger} ${message}" fileName="${basedir}/nlog_sample_file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</nlog>
这是我的代码生成日志:
Here's my code generating the log:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
namespace NLogSample
{
class Program
{
static void Main(string[] args)
{
try
{
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", "This message from the LogInfoEvent will not be used.");
theEvent.Properties["Message"] = "This message from the LogInfoEvent Message property will be used.";
logger.Debug(theEvent);
logger.Debug("Does the sequence ID show up in this message?");
string formattedMessage = theEvent.FormattedMessage;
string eventString = theEvent.ToString();
}
catch (Exception ex)
{
int a = 1;
}
}
}
}
最后,这是一条消息示例:
Finally, here is a sample of the message:
2014-10-08 10:14:13.5525 NLogSample.Program日志事件:Logger =''Level = Debug Message ='将不使用LogInfoEvent中的此消息.' SequenceID = 2
2014-10-08 10:14:13.5525 NLogSample.Program Log Event: Logger='' Level=Debug Message='This message from the LogInfoEvent will not be used.' SequenceID=2
我正在Win7 Pro计算机上使用Visual Studio 2012.
I am working in Visual Studio 2012 on a Win7 Pro machine.
非常感谢!
RobR
推荐答案
我必须这样做
class MyLogEventInfo : LogEventInfo {
public override string ToString() {
return base.FormattedMessage;
}
}
...
var theEvent = new MyLogEventInfo();
theEvent.Message = "This message from the LogInfoEvent will not be used.";
logger.Debug(theEvent);
这篇关于NLog:如何控制LogEventInfo对象中消息的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!