7

Is there a way to get the full filename from the Log Class? The logger creates a file with a format like C:\MyPath\log-20160631.txt

I can not access the source filename which i used for the init of the logger.

Edit: Here is the init of the logger:

Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.LiterateConsole()
            .WriteTo.RollingFile(@"C:\MyPath\log.txt")
            .CreateLogger();

In every location in the code i can use e.g. Log.Information() but how i get the Sink information? I want to get the filename which i passed to rolling file sink.

My current workaround is to generate the real file manually (crazy ugly code):

public string LogFilename
{
   get
   {
      string path = Path.GetDirectoryName(LogFilenameTemplate);
      string filenameWithoutExtension = Path.GetFileNameWithoutExtension(LogFilenameTemplate);
      string extension = Path.GetExtension(LogFilenameTemplate);
      string date = DateTime.Now.ToString("yyyyMMdd");
      string fullFilename = Path.Combine(path, filenameWithoutExtension + "-" + date + extension);
      return fullFilename;
   }
}

Format i got from GitHub Repo.

Suplanus
  • 1,523
  • 16
  • 30
  • 1
    It's not clear what you mean by "I can not access the source filename which i used for the init of the logger.". Please post your serilog initialization code and clarify exactly where and why you need the filename. – PatrickSteele Oct 11 '16 at 13:28
  • I added the example code and a extended description and a current workaround. – Suplanus Oct 12 '16 at 05:12
  • From skimming [through the code](https://github.com/serilog/serilog-sinks-rollingfile/tree/dev/src/Serilog.Sinks.RollingFile/Sinks/RollingFile), I don't think it's possible to get the filename currently being used. I guess another question would be why to do you need it? Perhaps there's another way of doing what you need to do without knowing filename. – PatrickSteele Oct 12 '16 at 11:56
  • I pass the Logger to an other part of an application (programed not by me). And there is a need to open the log file in the UI. So i should pass :) the filename as well, with the ugly workaround. – Suplanus Oct 12 '16 at 14:00
  • 1
    If you absolutely need to use the filesystem to share access to the logs, make sure you [set the `shared` flag to `true`](https://nblumhardt.com/2016/08/atomic-shared-log-file-writes/). But it might be easier to find a different way to share the log data than relying on a filename. – PatrickSteele Oct 12 '16 at 14:28

1 Answers1

9

No, there's no way to retrieve the filename from Serilog. Your best available option is to use the System.IO classes to list files in the directory, and then open the one with the most recent modification date.

Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101