How to Add Custom Logging in ASP.NET Core
If you want to create a custom logging system for your ASP.NET Core application, continue reading to get the advice of an expert.
Join the DZone community and get the full member experience.
Join For Freeasp.net core is pretty flexible, customizable, and extendable. you are able to change almost everything. even the logging. if you don't like the built-in logging, you are able to plug in your own logger or an existing logger like log4net, nlog, elmah. in this post, i'm going to show you how to add a custom logger.
the logger i show you just writes out to the console, but just for one single log level. the feature is to configure different font colors per loglevel. so this logger is called
coloredconsolelogger
.
general
to add a custom logger, you need to add an
iloggerprovider
to the
iloggerfactory
, that is provided in the method configure in the
startup.cs
:
loggerfactory.addprovider(new customloggerprovider(new customloggerconfiguration()));
the
iloggerprovider
creates one or more
ilogger
which are used by the framework to log the information.
the configuration
the idea is to create different colored console entries per log level and event id. to configure this we need a configuration type like this:
public class coloredconsoleloggerconfiguration
{
public loglevel loglevel { get; set; } = loglevel.warning;
public int eventid { get; set; } = 0;
public consolecolor color { get; set; } = consolecolor.yellow;
}
this sets the default level to
warning
and the color to
yellow
. if the
eventid
is set to 0, we will log all events.
the logger
the logger gets a name and the configuration passed in via the constructor. the name is the category name, which usually is the logging source, eg. the type where the logger is created in:
public class coloredconsolelogger : ilogger
{
private readonly string _name;
private readonly coloredconsoleloggerconfiguration _config;
public coloredconsolelogger(string name, coloredconsoleloggerconfiguration config)
{
_name = name;
_config = config;
}
public idisposable beginscope<tstate>(tstate state)
{
return null;
}
public bool isenabled(loglevel loglevel)
{
return loglevel == _config.loglevel;
}
public void log<tstate>(loglevel loglevel, eventid eventid, tstate state, exception exception, func<tstate, exception, string> formatter)
{
if (!isenabled(loglevel))
{
return;
}
if (_config.eventid == 0 || _config.eventid == eventid.id)
{
var color = console.foregroundcolor;
console.foregroundcolor = _config.color;
console.writeline($"{loglevel.tostring()} - {eventid.id} - {_name} - {formatter(state, exception)}");
console.foregroundcolor = color;
}
}
}
we are going to create a logger instance per category name with the provider.
the loggerprovider
the
loggerprovider
is the guy who creates the logger instances. maybe it is not needed to create a logger instance per category, but this makes sense for some loggers, like nlog or log4net. doing this you are also able to choose different logging output targets per category if needed:
public class coloredconsoleloggerprovider : iloggerprovider
{
private readonly coloredconsoleloggerconfiguration _config;
private readonly concurrentdictionary<string, coloredconsolelogger> _loggers = new concurrentdictionary<string, coloredconsolelogger>();
public coloredconsoleloggerprovider(coloredconsoleloggerconfiguration config)
{
_config = config;
}
public ilogger createlogger(string categoryname)
{
return _loggers.getoradd(categoryname, name => new coloredconsolelogger(name, _config));
}
public void dispose()
{
_loggers.clear();
}
}
there's no magic here. the method
createlogger
creates a single instance of the
coloredconsolelogger
per category name and stores it in the dictionary.
usage
now we are able to use the logger in the
startup.cs
public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
{
loggerfactory.addconsole(configuration.getsection("logging"));
loggerfactory.adddebug();
// here is our customlogger
loggerfactory.addprovider(new coloredconsoleloggerprovider(new coloredconsoleloggerconfiguration
{
loglevel = loglevel.information,
color = consolecolor.blue
}));
loggerfactory.addprovider(new coloredconsoleloggerprovider(new coloredconsoleloggerconfiguration
{
loglevel = loglevel.debug,
color = consolecolor.gray
}));
but this doesn't really look nice from my point of view. i want to use something like this:
loggerfactory.addcoloredconsolelogger(c =>
{
c.loglevel = loglevel.information;
c.color = consolecolor.blue;
});
loggerfactory.addcoloredconsolelogger(c =>
{
c.loglevel = loglevel.debug;
c.color = consolecolor.gray;
});
this means we need to write at least one extension method for the
iloggerfactory
:
public static class coloredconsoleloggerextensions
{
public static iloggerfactory addcoloredconsolelogger(this iloggerfactory loggerfactory, coloredconsoleloggerconfiguration config)
{
loggerfactory.addprovider(new coloredconsoleloggerprovider(config));
return loggerfactory;
}
public static iloggerfactory addcoloredconsolelogger(this iloggerfactory loggerfactory)
{
var config = new coloredconsoleloggerconfiguration();
return loggerfactory.addcoloredconsolelogger(config);
}
public static iloggerfactory addcoloredconsolelogger(this iloggerfactory loggerfactory, action<coloredconsoleloggerconfiguration> configure)
{
var config = new coloredconsoleloggerconfiguration();
configure(config);
return loggerfactory.addcoloredconsolelogger(config);
}
}
with this extension method, we are able to pass in an already defined configuration object, we can use the default configuration or use the configure action as shown in the previous example:
loggerfactory.addcoloredconsolelogger();
loggerfactory.addcoloredconsolelogger(new coloredconsoleloggerconfiguration
{
loglevel = loglevel.debug,
color = consolecolor.gray
});
loggerfactory.addcoloredconsolelogger(c =>
{
c.loglevel = loglevel.information;
c.color = consolecolor.blue;
});
conclusion
this is how the output of that nonsense logger looks:
now it's up to you to create a logger that writes the entries to a database, log file or whatever or just add an existing logger to your asp.net core application.
Published at DZone with permission of Jurgen Gutsch. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments