## Serilog (C#): How to get the current MethodName, FileName/Path and LineNumber without reflection ## This is a simple setup for reflectionless logging with serilog using caller information (using a single static class). See also https://stackoverflow.com/a/46905798 ### Log.cs ### Create your own ``Log.cs`` in your Root-Namespace (you can use the class below). This class is needed to detect from where the call is coming from; it uses [Caller-Information](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information) to speed up the program execution, because the attributes are resolved at compiletime. You can now also remove all ``using Serilog;``-imports - if you have any - in the classes where you want to log, because the ``Log.cs`` is everywhere in the namespace visble and easy accessible. ### Serilog-Output Template ### Now you can use the added properties (here: ``MemberName``, ``FilePath``, ``FileName``, ``LineNumber``) in your outputTemplate: _:warning: Note: For more performance you can remove/uncomment unused properties, here e.g. ``FilePath`` and ``LineNumber`` in ``SetContext(...)``_ ### Final Example ### OutputTemplate: `{Timestamp:HH:mm:ss,fff} {Level:u3} {FileName} [{MemberName}] {Message:lj}{NewLine}{Exception}` ```csharp namespace Demo { public class TestClass { public void TestMethod() { Log.Info("Some test"); } } } ``` Produces the following output: ``18:16:40,183 INFO TestClass [TestMethod] Some test`` ### Changelog * 2020-03-21: Tuned docs a bit; updated and reformatted the Log.cs class