Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ASP.NET Core: Implementing the Syslog Logger

DZone's Guide to

ASP.NET Core: Implementing the Syslog Logger

Read on to learn how to use the Syslog logger, and how to send messages to this logger using your ASP.NET Core web application.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

This blog post shows you how to log messages to a Syslog server from ASP.NET Core applications.

The Syslog server is a popular logs server from the Linux world. It is usually a separate box or virtual machine that accepts log messages but it is not accessible by external users. It can be especially useful for web applications, as hackers can't open a way to your internal network, and thus logs remain safe, as malicious users cannot access them.

Syslog Logger Provider

Logger Provider creates an instance of a logger with given parameters and returns it. We will use it later when introducing Syslog Logger to Logger Factory.

public class SyslogLoggerProvider : ILoggerProvider
{
    private string _host;
    private int _port;

    private readonly Func<string, LogLevel, bool> _filter;

    public SyslogLoggerProvider(string host, int port, Func<string, LogLevel, bool> filter)
    {
        _host = host;
        _port = port;

        _filter = filter;
    }

    public ILogger CreateLogger(string categoryName)
    {
        return new SyslogLogger(categoryName, _host, _port, _filter);
    }

    public void Dispose()
    {
    }
}

ILoggerProvider extends IDisposable, and this is why we need theDispose() method here. As we have nothing to dispose of, the method is empty.

Syslog Logger

Logger is created by the logger provider. All the parameters we use with it will land here.

public class SyslogLogger : ILogger
{
    private const int SyslogFacility = 16;

    private string _categoryName;
    private string _host;
    private int _port;

    private readonly Func<string, LogLevel, bool> _filter;

    public SyslogLogger(string categoryName,
                        string host,
                        int port,
                        Func<string, LogLevel, bool> filter)
    {
        _categoryName = categoryName;
        _host = host;
        _port = port;

        _filter = filter;
    }

    public IDisposable BeginScope<TState>(TState state)
    {
        return NoopDisposable.Instance;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return (_filter == null || _filter(_categoryName, logLevel));
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        if (!IsEnabled(logLevel))
        {
            return;
        }

        if (formatter == null)
        {
            throw new ArgumentNullException(nameof(formatter));
        }

        var message = formatter(state, exception);

        if (string.IsNullOrEmpty(message))
        {
            return;
        }

        message = $"{ logLevel }: {message}";

        if (exception != null)
        {
            message += Environment.NewLine + Environment.NewLine + exception.ToString();
        }

        var syslogLevel = MapToSyslogLevel(logLevel);
        Send(syslogLevel, message);
    }

    internal void Send(SyslogLogLevel logLevel, string message)
    {
        if (string.IsNullOrWhiteSpace(_host) || _port <= 0)
        {
             return;
        }

        var hostName = Dns.GetHostName();
        var level = SyslogFacility * 8 + (int)logLevel;
        var logMessage = string.Format("<{0}>{1} {2}", level, hostName, message);
        var bytes = Encoding.UTF8.GetBytes(logMessage);

        using (var client = new UdpClient())
        {
             client.SendAsync(bytes, bytes.Length, _host, _port).Wait();
        }
    }

    private SyslogLogLevel MapToSyslogLevel(LogLevel level)
    {
        if (level == LogLevel.Critical)
            return SyslogLogLevel.Critical;
        if (level == LogLevel.Debug)
            return SyslogLogLevel.Debug;
        if (level == LogLevel.Error)
            return SyslogLogLevel.Error;
        if (level == LogLevel.Information)
            return SyslogLogLevel.Info;
        if (level == LogLevel.None)
            return SyslogLogLevel.Info;
        if (level == LogLevel.Trace)
            return SyslogLogLevel.Info;
        if (level == LogLevel.Warning)
            return SyslogLogLevel.Warn;

        return SyslogLogLevel.Info;
    }
}

To make this class work we need to use theSyslogLogLevel enumerator.

public enum SyslogLogLevel
{
    Emergency,
    Alert,
    Critical,
    Error,
    Warn,
    Notice,
    Info,
    Debug
}

We also need the NoopDisposable class that I borrowed from the blog post,  Building Application Insights Logging Provider for ASP.NET Core by Hisham Bin Ateya.

public class NoopDisposable : IDisposable
{
    public static NoopDisposable Instance = new NoopDisposable();

    public void Dispose()
    {
    }
}

Now we have our logger implemented and it’s time to write the extension methods that introduce it to Logger Factory.

Introducing Syslog to Logger Factory

We will follow the same pattern we use with our other loggers, including those that come with ASP.NET Core. Loggers are introduced to Logger Factory by the AddSomething()] method like AddConsole(), AddDebug(), etc. Our method is called AddSyslog().

public static class SyslogLoggerExtensions
{
    public static ILoggerFactory AddSyslog(this ILoggerFactory factory,
                                    string host, int port,
                                    Func<string, LogLevel, bool> filter = null)
    {
        factory.AddProvider(new SyslogLoggerProvider(host, port, filter));
        return factory;
    }
}

Here is how we introduce the Syslog Logger to Logger Factory:

loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddFile("wwwroot/logs/ts-{Date}.txt");
loggerFactory.AddSyslog("192.168.210.56", 514);

When we run our application, we can see something like this logged to our Syslog server:

Image title

Wrapping Up

ASP.NET Core logging mechanism may seem like something big at first, but they are actually easy. Writing messages to the Syslog server is easy too. We implemented a Syslog logger provider, and a logger and extension methods for Logger Factory. Introducing the Syslog logger to Logger Factory follows the same AddSomething() pattern as other loggers do. It’s easy to try it out on Windows using Visual Syslog Server by Max Belkov.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
web dev ,logging ,asp.net core

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}