How do I change the filename of a log file?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

How do I change the filename of a log file?

Angelo Trivelli
Hi,

I have a config file setup to log everything properly to a particular file (for example "mylog.log")

What I would like to do now is to change the name of the logfile to something else before I start logging to it, where the filename is determined at runtime.

I know this can be done by configuring NLog entirely programmatically, but I want to use a existing configuration and simply modify the target filename.

How can this be done?

Thanks!
Reply | Threaded
Open this post in threaded view
|

Re: How do I change the filename of a log file?

degloff
I did it this way e.g. in the Main function or at the beginning of my program:

            // change the log file specified in the NLog config file
            // supposing that a target "file" as file target in config file
            FileTarget target = LogManager.Configuration.FindTargetByName("file") as FileTarget;
            String logfile = "somepath" + "/some_name.txt";
            target.FileName = logfile;

HTH

Daniel
Reply | Threaded
Open this post in threaded view
|

Re: How do I change the filename of a log file?

Kaboo
This post was updated on .
Using degloff idea as a starting point. I wanted to create two log files; one detailed and one only showing the critical things. But the user has the right to change the directory to where they want the logs to be stored. Thus, I created this:

foreach(FileTarget target in LogManager.Configuration.AllTargets.Where(t => t is FileTarget).Cast())
{
  var filename = Path.GetFileName(target.FileName.ToString().Trim('\''));
  target.FileName = Path.Combine(logDir, filename);
}

Hope this helps.