简体   繁体   中英

NLog not creating log files, configuration through code

Using NLog v4.6.8.

It is being configured through code as follows:

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();
    }
}

Typical usage is as follows:

Logger.Info("Doing something");

There is no log file in the assembly's directory. Why could this be?

Some troubleshooting advice found suggests that a common reason for this is that NLog's config file is not being copied to the output directory. However, there is no config file in the project or solution. There is only a reference to the required DLL.

On first sight your code looks valid. Of course make sure you will call Logger.ConfigureLogger first.

I think this is a write permission error. You could try writing to the temp folder. Also you could enable the internal log (from code)

// 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;

To be clear, there is no need for XML configuration - that's optional

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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