MicroLite 5.0 – Changes to Logging

In MicroLite 5.0, we have updated the logging API. The information in this post supersedes the information in the Using Logging in Custom Listeners post.

The extension methods which have been removed and the LogManager has been updated so that it will return an empty logger if none is configured. This means that as long as you call MicroLite.Logging.LogManager.GetCurrentClassLog(); you will be returned with an ILog instance.

The ILog interface has been updated with the following properties which allow you to check whether the log is configured at a given level before calling the corresponding log method. This can save on unnecessary calls to resource files and string formatting etc if the log isn’t capturing certain levels of data.

bool IsDebug { get; }
bool IsInfo { get; }
bool IsWarn { get; }
bool IsError { get; }
bool IsFatal { get; }

The ValidationListener in the Using Logging in Custom Listeners post would be updated as follows:

using MicroLite.Logging;

public class ValidationListener : MicroLite.Listeners.Listener
{
    private static ILog log = LogManager.GetCurrentClassLog();

    protected override BeforeInsert(object instance)
    {
        // This ensures that we only pay the cost of calling
        // .GetType() if we want to log the value anyway.
        if (log.IsDebug)
        {
            log.Debug(
                "Validating an {0} before insert",
                instance.GetType().Name);
        }

        ValidateObject(instance);
    }

    protected override BeforeUpdate(object instance)
    {
        // This ensures that we only pay the cost of calling
        // .GetType() if we want to log the value anyway.
        if (log.IsDebug)
        {
            log.Debug(
                "Validating an {0} before update",
                instance.GetType().Name);
        }

        ValidateObject(instance);
    }

    private void ValidateObject(object instance)
    {
        var warnings = Validator.GetWarnings(instance);
        var errors = Validator.GetErrors(instance);

        foreach (var warning in warnings)
        {
            if (log.IsWarn) { log.Warn(warning); }
        }

        foreach (var error in errors)
        {
            if (log.IsError) { log.Error(error); }
        }

        if (warnings.Count > 0 || errors.Count > 0)
        {
            throw new ValidationException(warnings, errors);
        }
    }
}
Advertisements

One thought on “MicroLite 5.0 – Changes to Logging

  1. Pingback: MicroLite 5.0 Released | MicroLite ORM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s