DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Trending

  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices
  • Agentic Systems and Design Patterns
  • Building a Software Factory With AI Agents and Workflows
  • AI-Era Cybersecurity, Part 1: Mapping Glasswing, Daybreak, Lightwell and the Tools Racing to Find and Fix Bugs

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. How to Add Custom Logging in ASP.NET Core

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.

By 
Jurgen Gutsch
·
May. 08, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
26.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

asp.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.

ASP.NET Core ASP.NET

Published at DZone with permission of Jurgen Gutsch. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook