Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
adras opened this issue Feb 4, 2023 · 2 comments
Closed

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

adras opened this issue Feb 4, 2023 · 2 comments
Labels

Comments

@adras
Copy link

adras commented Feb 4, 2023

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
Copy link
Author

adras commented Feb 4, 2023

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
Copy link
Member

You might want to read about FileLifecycleHooks. There's an example here: #191

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

@augustoproiete augustoproiete closed this as not planned Won't fix, can't repro, duplicate, stale Feb 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants