serilog / serilog-sinks-file

Write Serilog events to files in text and JSON formats, optionally rolling on time or size
Apache License 2.0
333 stars 117 forks source link

How can I get the filepath of the current RollingFile during runtime #275

Closed adras closed 1 year ago

adras commented 1 year ago

I would like to attach the current log to an email I'm plannig to send during runtime. I'm having a hard time figuring out how to do that though.

Here's my log initialization:

string logFilePath = "Test-{Date}.log";
            Log.Logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.RollingFile(logFilePath)
                .CreateLogger();

I saw related issues, but I couldn't figure out what exactly I need to do with my configuration to get the file path

adras commented 1 year ago

I'm going to hell for this, please help me

public static class LoggerExtensions
{
    public static string GetCurrentLogFilePath(this ILogger logger)
    {
        FieldInfo? sinkField = Log.Logger.GetType().GetField("_sink", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
        object sinkObject = sinkField?.GetValue(Log.Logger);
        FieldInfo? sinksField = sinkObject?.GetType().GetField("_sinks", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
        ILogEventSink[] sinks = (ILogEventSink[])sinksField?.GetValue(sinkObject);
        RollingFileSink rollingSink = (RollingFileSink)sinks?.Where(s => s.GetType() == typeof(RollingFileSink)).FirstOrDefault();
        FieldInfo? rollerField = rollingSink.GetType().GetField("_currentFile", BindingFlags.Instance | BindingFlags.NonPublic);
        FileSink fileSink = rollerField.GetValue(rollingSink) as FileSink;
        FieldInfo? streamField = fileSink?.GetType().GetField("_underlyingStream", BindingFlags.Instance | BindingFlags.NonPublic);
        FileStream stream = streamField?.GetValue(fileSink) as FileStream;

        string fileName = stream?.Name;

        return fileName;
    }
}
augustoproiete commented 1 year ago

You might want to read about FileLifecycleHooks. There's an example here: https://github.com/serilog/serilog-sinks-file/issues/191

For general usage questions, please use the serilog Stack Overflow tag and we'll do our best to get eyes on it!