Skip to content

Instantly share code, notes, and snippets.

@sunnamed434
Last active January 29, 2023 20:02
Show Gist options
  • Save sunnamed434/7cc01da7c434aa5f1a9966dc79d37ffb to your computer and use it in GitHub Desktop.
Save sunnamed434/7cc01da7c434aa5f1a9966dc79d37ffb to your computer and use it in GitHub Desktop.
Serilog bypass ForContext<T>()
public static class SerilogContextCallerExtensions
{
private const string CsharpFileExtension = ".cs";
public static ILogger ForContextFile(this ILogger source, [CallerFilePath] string caller = "")
{
caller = caller
.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.Last()
.Replace(CsharpFileExtension, string.Empty);
return source.ForContext(Constants.SourceContextPropertyName, caller);
}
}
// Default
logger.ForContext<SomeType>() // SomeType
// Now
logger.ForContextFile() // SomeType
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment