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.
Join the DZone community and get the full member experience.
Join For Freethis 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 the
dispose()
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 the
syslogloglevel
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:
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.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments