NLog 不创建日志文件,通过代码配置

NLog not creating log files, configuration through code

使用 NLog v4.6.8。

正在通过代码配置如下:

public class Logger
{
    public static void ConfigureLogger()
    {
        var config = new NLog.Config.LoggingConfiguration();

        // target where to log to
        string logFileName = @"\log.txt";
        string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        var logfile = new NLog.Targets.FileTarget("logfile") { FileName = path + logFileName, KeepFileOpen = true, OpenFileCacheTimeout = 5 };

        // delete the log file, if it exists.
        string fullFilePath = path + logFileName;
        if (File.Exists(fullFilePath))
        {
            File.Delete(fullFilePath);
        }

        // rules for mapping loggers to targets
        // minimum and maximum log levels for logging targets
        config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logfile);

        // apply config
        NLog.LogManager.Configuration = config;
    }

    // create an instance of the logger for each class
    public static NLog.Logger getLogger()
    {
        return NLog.LogManager.GetCurrentClassLogger();
    }

    // Flush and close down internal threads and timers.
    public static void flushLogger()
    {
        NLog.LogManager.Shutdown();
    }
}

典型用法如下:

Logger.Info("Doing something");

程序集目录中没有日志文件。为什么会这样?

发现的一些故障排除建议表明,一个常见的原因是 NLog 的配置文件没有被复制到输出目录。但是,项目或解决方案中没有配置文件。只有对所需 DLL 的引用。

乍一看,您的代码看起来是有效的。当然,请确保您会先致电 Logger.ConfigureLogger

我认为这是一个写权限错误。您可以尝试写入临时文件夹。您也可以启用内部日志(来自代码)

// In case of a console application:
NLog.Common.InternalLogger.LogToConsole = true;

// otherwise to file: recommended to use the temp dir
NLog.Common.InternalLogger.LogFile = "c:\temp\log-internal.txt";

// Also needed. Try info level or otherwise debug and trace to get more details
NLog.Common.InternalLogger.LogLevel = LogLevel.Info;

需要说明的是,不需要 XML 配置 - 这是可选的