Simple way to write to syslog
aka /dev/log
aka /var/log/syslog
in .NET Core on Linux. Consists of one short C# file (70 lines!) that you can throw into your project. Tested in ASP.NET Core 5.
Syslog.Write(Syslog.Level.Warning, "MyAwesomeApp", "something went wrong");
.NET Core (aka .NET 5 and later) does not have a built-in logging provider for linux. The official recommendation is to use a 3rd party logger, like Serilog, NLog, Log4Net etc.
All heavyweight large libraries.
There's an ongoing discussion if a default logger should be a part of .NET runtime, but it's stall.
Where do you place the logs? How do you grant permissions to that location? How should the files be formatted? When do the files rotate/roll over? Microsoft couldn't decide and... simply ignored the problem.
Why reinvent the wheel?!
Almost every linux distro comes with a built-in feature called syslog
. It takes care of everything: queues messages, writes to log files, rotates files (via "logrotate"), and exists on literally every Linux machine. It has lots of ways to send messages to it: UDP-listener, TCP-listener, a "Unix socket" at /dev/log
, a logger
CLI command or a syslog()
system function etc.
For Windows folks: think of it as an EventLog.Write
, but for Linux
If you're running an app inside a container, docker logs
will show these logs, zero configuration.
Just use the good old DllImport
to reference the external libc
library, and call the original syslog function. That's it. No Nugets, no dependency-injection.
Happy coding.
Run sudo apt-get install rsyslog
rsyslog
might be present but it's not running (known issue with WSL2 for example). Check that its running, if not - start it:
$ service rsyslog status
* rsyslogd is not running
$ sudo service rsyslog start
Then test that logging actually works:
$ logger testtesttest
$ tail -1 /var/log/syslog
Oct 11 13:51:18 DESKTOP-CDBR5NK jazz: testtesttest
No worries, the code checks if it runs on Windows or Linux before proceeding.