3

Using the snippet below which uses NLog how can this be done using Enterprise Library 5.0 Logging?

    private Logger _logger;
    public NLogger() {            
        _logger = LogManager.GetCurrentClassLogger();
    }

    public void Info(string message) {
        _logger.Info(message);
    }

    public void Warn(string message) {
        _logger.Warn(message);
    }
4

1 回答 1

5

You are looking for something like this:

private LogWriter _logger;
public void EntLibLogger()
{
    _logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>(); ;
}

public void Info(string message)
{
    LogEntry log = new LogEntry();
    log.Message = message;
    log.Categories.Add("Information");
    log.Priority = Priority.Normal;
    log.Severity = TraceEventType.Information;
    _logger.Write(log);
}

public void Warn(string message)
{
    LogEntry log = new LogEntry();
    log.Message = message;
    log.Categories.Add("Warning");
    log.Priority = Priority.High;
    log.Severity = TraceEventType.Warning;
    _logger.Write(log);
}

public void Error(string message, int EventID, Dictionary<String,String> dictMessage)
{
    LogEntry log = new LogEntry();
    log.Message = message;
    log.Categories.Add("Error");
    log.Priority = Priority.Highest;
    log.Severity = TraceEventType.Error;
    log.EventId = EventID;
    _logger.Write(log, dictMessage);
}

Setting up the configuration settings in app.config is the fiddly bit.

My recommendation is to make EventID globally unique per call (system documentation always includes the spreadsheet with these numbers and the project/file/line# these occur at). This way, if the app is in production, it is extremely likely that you'll get 1 row from the log and you'll have to be able to identify where in the source this logging call came from. I usually add a dictionary of stuff for local variables and their values for debugging purposes. One place wants the previous values logged, so the audit events always include a dictionary.

The way it logs by default in the database, Entlib stores "category" as a string in both the categories and log table. Severity, priority and EventID are stored as ints. FormattedMessage is a large clump of stuff that is defined in the formatters section, and also includes the contents (the key value pairs) of dictionaries - if used.

Categories is a collection because there may be some times you want to log everything in the database, but certain messages also write to the event log and/or send the dev a text message to get their fanny perpendicular in to work asap. One place I worked at used an Iridium pager to let the designated person know that the servers were down/in trouble, since they liked mountain climbing, they were frequently where no cell coverage existed.

于 2010-11-07T23:59:37.243 回答