如何使用NLog在我当前的目录中创建文本文件?

use*_*369 5 c# console nlog

我是第一次使用Nlog.我的目标是只写一个文本文件.

在main.c我有

class Program
{
    private static Logger logger = LogManager.GetCurrentClassLogger();

static void Main(string[] args)
{
        logger.Trace("Sample trace message");
        logger.Debug("Sample debug message");
        logger.Info("Sample informational message");
        logger.Warn("Sample warning message");
        logger.Error("Sample error message");
        logger.Fatal("Sample fatal error message");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Nlog.config文件如下:

<?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">

    <targets>
        <target name="logfile" xsi:type="File" fileName="file.txt" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="logfile" />
    </rules>
</nlog>
Run Code Online (Sandbox Code Playgroud)

但是我无法在当前目录中创建txt文件.

chr*_*dev 7

试试这个...

<targets>
    <target name="logfile" xsi:type="File" fileName="${basedir}/file.txt" />
</targets>
Run Code Online (Sandbox Code Playgroud)

看看这里,introduction to NLog.


Nic*_*k V 7

您是否将NLog.config'副本设置为'始终复制'到输出目录?

如果你按照他们的教程,你应该让它工作.


Wah*_*tar 6

这对我有用${CurrentDir}

例如

<target xsi:type="File" 
    name="ownFile-web" 
    fileName="${CurrentDir}\Logs\nlog-web-${shortdate}.log"
    layout="${longdate}|${event-properties:item=EventId_Id}| [${uppercase:${level}}]${newline}Logger: ${logger}${newline}url: ${aspnet-request-url}${newline}CallSite: ${callsite}${newline}Message: ${message}${onexception:${newline}EXCEPTION:${exception:format=tostring}}${newline}-------${newline}" />
Run Code Online (Sandbox Code Playgroud)

https://github.com/NLog/NLog/wiki/CurrentDir-Layout-Renderer