繁体   English   中英

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 的配置文件没有被复制到 output 目录中。 但是,项目或解决方案中没有配置文件。 只需要参考所需的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 配置 - 这是可选的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM