0

I discovered a way to silently kill my C# program by typing Log.Error instead of Log.Logger.Error. C# happily accepts it and it swallows exceptions so the programs just goes kaput.

It would be nice to simplify it and I've tried various usings to simplify it. Things like

using logError = static Serilog.Log.Logger.Error;

But nothing that works. Is it possible?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
David Bolton
  • 168
  • 3
  • 12
  • 3
    use dependency injection to get a `ILogger` – Daniel A. White Mar 26 '22 at 14:38
  • 1
    Your application wireup either guarantees environmental invariants or it does not. The well documented standard wireup always establishes `Log.Logger` first for this reason (and there are bootstrap loggers etc). So I'd not over think this too much – Ruben Bartelink Mar 26 '22 at 22:16
  • I [used to](https://stackoverflow.com/a/13714035/120955) recommend using dependency injection for the logger, but over time I've come to realize that the value proposition of dependency injection (testability, etc.) largely doesn't apply to cross-cutting concerns like logging. I [now recommend](https://stackoverflow.com/a/59416660/120955) using [Fody Anotar](https://github.com/Fody/Anotar). The syntax is simply `LogTo.Error(...)`, but you get all kinds of great contextual goodness added in at runtime. – StriplingWarrior Mar 27 '22 at 23:57

2 Answers2

1

Log.Error() and Log.Logger.Error() are the same call - one is just shorthand that forwards to the other. The source of your problem will be somewhere else.

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

As Nicholas pointed out in his answer, Log.Error() & Log.Logger.Error() are the same; Log.Logger.Error() just forward the call to Log.Error(). Or is it vice versa? I forget.

If no logger has been assigned to the static Log.Logger instance, then the OOB SilentLogger is used. Where all logging is "swallowed" by the SilentLogger.

If you really want to use the static Log.Logger instance, then a logger needs to be assigned. For example, the quickest/easiest logger to create/assign is the ConsoleLogger:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateLogger();

Once you've assigned the ConsoleLogger, all logging will be output to the console. Other types of loggers can be assigned as well.

Best practices would recommend using Dependency Injection, though. Review the Serilog Configuration Basics for more information.

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140