【问题标题】:NLog not creating log files, configuration through codeNLog 不创建日志文件,通过代码配置
【发布时间】:2020-11-12 18:13:57
【问题描述】:

使用 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 的引用。

【问题讨论】:

  • 安装 NLog xml(config) 包:Install-Package NLog.Xml
  • @Li-JyuGao 是不是必须是同一个版本,而且必须设置复制到输出目录?
  • @Li-JyuGao 完成我在上面评论中描述的操作后,仍然没有日志文件。
  • 是的,版本相同。在项目解决方案中,配置的属性应该设置为[总是复制到输出目录]。
  • 您不需要 nlog.xml 包。这是一个旧的 3rd 方包,在这种情况下不推荐或有用

标签: c# .net configuration nlog


【解决方案1】:

乍一看,您的代码看起来是有效的。当然,请确保您先致电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 配置 - 这是可选的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多