NLog使用NLog.config动态更改文件名

时间:2016-05-19 15:01:46

标签: c# nlog common.logging

如何使用C#中的变量动态更改FileName?我的想法是创建一个像Log_<UserId_From_DB>_${date:format=yyyy-MM-dd}.log这样的日志文件。 有什么想法吗?

3 个答案:

答案 0 :(得分:7)

另一种选择是使用Global Diagnostic Context - $(GDC)

在C#中设置值

GlobalDiagnosticsContext.Set("UserId_From_DB","42");

在config(nlog.config)中:

<target type="file" filename="Log_${gdc:item=UserId_From_DB}_${date:format=yyyy-MM-dd}.log" ..>

请避免在运行时修改NLog变量(请参阅下面的上一个答案)。它们应该被视为只读,因为它们不是线程安全的。如果重新加载LoggingConfiguration,NLog变量也会受到影响。

NLog变量的上一个答案:

在C#中设置值

LogManager.Configuration.Variables["UserId_From_DB"] = "42";

在config(nlog.config)中:

<target type="file" filename="Log_${var:UserId_From_DB}_${date:format=yyyy-MM-dd}.log" ..>

如果再次设置该值,文件名将自动更改。

答案 1 :(得分:2)

虽然发布的答案有效,但存在并发问题。该变量是全局变量,您可能会遇到冲突。

有更好的解决方案。有一种方法可以将事件属性传递给NLog。

Link to the relevant NLog documentation

假设您要记录一条错误消息:

Logger myLog = LogManager.GetLogger(name);
LogLevel level = LogLevel.Error;
string message = "This is an error message!";

您将此信息转换为LogEventInfo对象:

LogEventInfo logEvent = new LogEventInfo(level , myLog.Name, message);

然后可以向该事件添加属性(可以自由选择字符串索引):

logEvent.Properties["MySpecialValue"] = "SPECIAL";

然后您写入日志:

myLog.Log(logEvent);

这里有趣的是,在您的NLog配置中,您可以在Nlog文档将其称为“布局”值的任何字段中使用此自定义属性

您在布局中使用${event-properties:item=MySpecialValue}来访问属性。例如:

<target xsi:type="File" 
        name="file" 
        fileName="${basedir}/logs/${event-properties:item=MySpecialValue}/my_${event-properties:item=MySpecialValue}_file.log"
        layout="${event-properties:item=MySpecialValue} ${message}" />

按照发布的示例,您将获得一个名为SPECIAL的文件夹,其中有一个名为my_SPECIAL_file.log的日志文件,您可以在其中找到消息SPECIAL This is an error message!。只是为了证明您可以通过许多不同的方式和形状使用此自定义值。


我通常使用它来进行特定于实体的日志记录(日志的文件名等于实体的ID值),这与您在此处要做的基本上相同。

快速提示,我倾向于将NLog Logger包装在我自己的类中:

public class UserLogger
{
    private readonly Logger _log;
    private readonly User _user;

    public UserLogger(User u)
    {
        _user = u;
        _log = LogManager.GetCurrentClassLogger();
    }

    public void Error(string message)
    {
        LogEventInfo logEvent = 
                 new LogEventInfo(LogLevel.Error, _log.Name, message);

        logEvent.Properties["UserId"] = _user.Id;

        _log.Log(logEvent);
    }
}

这只是一个入门的简单示例。我在这里使用的一个很酷的功能是,我已经使用UserId值定义了日志的文件名(在Nlog.Config目标中),因此可以确保每个用户都记录到自己的唯一日志文件中。 / p>

这样,您可以强制要登录到“用户日志”目标时知道用户ID。另外,它还可以将NLog依赖项与调用代码巧妙地分离。

答案 2 :(得分:1)

假设您的nlog.config文件中有一个名为mylogfile.log的日志文件

FileTarget target = LogManager.Configuration.FindTargetByName("mylogfile.log") as FileTarget; 
String customlog = "Log_" +  GetUserId(UserId_From_DB) + "_" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; 
target.FileName = customlog;