1

I'm using Nlog to write log files. It is working perfectly unless we have the log file open with Microsoft Excel. However if I open using notepad/notepad++ it is working correctly. Any idea to log the messages even if the file is opened with Excel.

Here is my NLog configuration code.

public class NLogLogger
{
    public static Logger Instance { get; private set; }

    public NLogLogger()
    {
        // Step 1. Create configuration object 
        LoggingConfiguration config = new LoggingConfiguration();

        // Step 2. Create targets and add them to the configuration 

        FileTarget fileTarget = new FileTarget();
        config.AddTarget("file", fileTarget);

        // Step 3. Set target properties 
        CsvLayout csvLayout = new CsvLayout();

        CsvColumn dateColumn = new CsvColumn() { Name = "Time", Layout = @"${date:format=dd.MM.yyyy HH\:mm\:ss}" };
        csvLayout.Columns.Add(dateColumn);

        CsvColumn levelColumn = new CsvColumn() { Name = "Level", Layout = @"${level:uppercase=true}" };
        csvLayout.Columns.Add(levelColumn);

        CsvColumn loggerColumn = new CsvColumn() { Name = "Logger", Layout = @"${logger}" };
        csvLayout.Columns.Add(loggerColumn);

        CsvColumn messageColumn = new CsvColumn() { Name = "Message", Layout = @"${message}" };
        csvLayout.Columns.Add(messageColumn);

        CsvColumn exceptionColumn = new CsvColumn() { Name = "Exception", Layout = @"${exception:format=ToString}" };
        csvLayout.Columns.Add(exceptionColumn);

        fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
        fileTarget.ArchiveEvery = FileArchivePeriod.Day;
        fileTarget.FileName = "${basedir}/file.csv";
        fileTarget.Layout = csvLayout;

        // Step 4. Define rules
        LoggingRule rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
        config.LoggingRules.Add(rule);

        // Step 5. Activate the configuration
        LogManager.Configuration = config;

        InternalLogger.LogFile = @"c:\temp\LoggerErrors.txt";

        // set internal log level
        InternalLogger.LogLevel = LogLevel.Trace;

        // Example usage
        Instance = LogManager.GetLogger("NLogLogger");   
    }

    public void LogError(Exception exception, string message = "")
    {
        Instance.ErrorException(message, exception);
    }
}

2 Answers 2

4

You can't log to the file when it is opened in excel in default mode, because excel will lock the file. You can first copy the file and then open the copied file in excel. This will leave the original file unlocked for logging. Notepad will not lock the file when it is opened.

However you can also make excel open the file as readonly with the /r switch:

EXCEL.EXE /r <your file name>

And you can change the default in your registry:

[HKEY_CLASSES_ROOT\Excel.CSV\shell\Open_in_read_only_Excel]
@="Open read-only in Excel"

[HKEY_CLASSES_ROOT\Excel.CSV\shell\Open_in_read_only_Excel\command]
@="\"C:\\Program Files (x86)\\Microsoft Office\\Office12\\EXCEL.EXE\" /r \"%1\""
4
  • Thanks for the answer. But how I will know whether the user is opened the file or not? Because after I have opened my log file with excel, exceptions or warning messages was not thrown by Nlog if logging is failed. Oct 22, 2013 at 14:31
  • Actually you can, sorry for my first awnser. Excel can open files in readonly mode. This will not lock your file.
    – Peter
    Oct 22, 2013 at 14:35
  • 1
    Note that by wrapping your NLog Logger the way that you have, you lose the ability to log call site information (the call site will always be your wrapper's logging method(s)). Also, every logging statement's "logger" value (you can configure to have this logged to your output via the logger LayoutRenderer) will be the typename of your logger wrapper.
    – wageoghe
    Oct 22, 2013 at 14:38
  • @wageoghe: Thanks for your info and your answer(stackoverflow.com/a/5136555/1537422). I will change my code. Oct 22, 2013 at 14:44
2

Not an answer to your question, but the way that you are wrapping your NLog Logger is not recommended. You lose a number of important NLog capabilities wrapping this way. You cannot control the logging level in different parts of your program. You cannot get good call site information (the call site will always be your wrapper's logging method(s) rather than the location in your code where logging statement is located). The "logger name" for every logging statement in your output will be the typename of your wrapper, making it that much harder to figure out where (in your code) the logging output is coming from.

Wrapping the logger is fine, as long it is done right. The keys are to use individual Logger instances (not a single Logger singleton) and to use the Logger.Log method, passing the typename of your wrapper as the first argument. See these answers to previous questions here on SO about wrapping NLog correctly:

How to retain callsite information when wrapping NLog

Nlog Callsite is wrong when wrapper is used

Problem matching specific NLog logger name

Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.