Catel help manual-catel. Core (6): Log Management

Source: Internet
Author: User
Tags log4net
1. Introduction

Since version 2.2, catel has used a custom log system. In this way, the reference to log4net can be removed. This modification is mainly made to avoid forcing users to use log4net. At the same time, log4net does not seem to be updated for a long time. Other log systems, such as nlog, seem to be growing. The new log system will allow many basic logs. In this way, logs will be very simple, and if needed, the real log will be executed by the user.

1.1 log and ilog

All logs are processed through the ilog interface. This interface is automatically registered to all objects in catel as log fields. The ilog interface only has one implementation. Each object can call the log automatic method to record any information.

In catel, there is only one class inheritance and ilog interface, that is, the log class, which ensures that the log message can be correctly formatted, logmessage is triggered when a message is written to the log.

A separate log type is created in Cate, so that developers can filter the logs they are interested in many logs.

1.2 logmanager

Logmanager is a management class that creates new logs for the type, but tracks all logs and log listening. to return a log of a specified class, you can use the following code.

 

private static readonly ILog Log = LogManager.GetCurrentClassLogger();

 

1.3 Use code to record logs

Using the code to record logs, the ilog interface implements some basic methods to record information and some additional data options. There are some extended methods to record exceptions, string formats, and so on, the following is an example of recording a resume:

Log.Warning("Customer ‘{0}‘ does not exist", customerId);

Alternatively, logs can be written if an exception is valid.

Log.Error(ex, "Failed to delete file ‘{0}‘", fileName);

1.4 record to the output window or Console

By default, catel does not add any listeners. Then, it contains an immediately available implementation to write logs to the output window or console. This is the debugloglistener. To register this listener, you can use the following code.

#if DEBUGLogManager.AddDebugListener();#endif

Before catel3.8Logmanager. registerdebuglistener ()

 

1.5 rewrite the global tag level

Starting from 3.8, you can rewrite the full-region log tag for all the listeners. If you want to do so, set the constant value on the logmanager. For example, force display of the debugging resume on all the listeners, use the following code:

LogManager.IsDebugEnabled = true;

To override the override setting, the setting value is null:

LogManager.IsDebugEnabled = null;
2. Custom listeners

Each listener can customize to return the logs of interest to the listener. In this way, if the listener is not interested, no event is returned. For example, if an error is returned, a new listener is created as follows:

var listener = new MyLogListener(); listener.IsDebugEnabled = false;listener.IsInfoEnabled = false;listener.IsWarningEnabled = false;listener.IsErrorEnabled = true;

By default, all logs are monitored.

3. Batch log listening

Batch log listening is a class that inherits the ibatchloglistener interface (most of the classes may inherit from batchloglistenerbase). This interface adds a flushmethod that allows the listener to be cleared, furthermore, log listening writes a slow listener storage. This will not access every source, but only batch processing.

3.1 All monitors of Flushing

When batch log listeners are used, it is important to clear all listeners when the application is abnormal or exits, because some important logs are lost if they are not persisted in the file.

Use the following code to flushing all listeners:

LogManager.FlushAll();
3.2 implement a custom ibatchloglistener

When implementing a general batch log listener, the common method is to inherit the batchloglistenerbase class, which has the following advantages:

1. batchloglistenerbase is thread-safe.

2. batchloglistenerbase automatically listens to flushes every 5 seconds.

You only need to implement the writelog Method to Determine the endpoint of persistent storage. The following is an example:

public class FileLogListener : BatchLogListenerBase{    private readonly string _filePath;    private readonly int _maxSizeInKiloBytes;    public FileLogListener(string filePath, int maxSizeInKiloBytes)    {        Argument.IsNotNullOrWhitespace(() => filePath);        _filePath = filePath;        _maxSizeInKiloBytes = maxSizeInKiloBytes;    }    protected override void WriteBatch(System.Collections.Generic.List<LogBatchEntry> batchEntries)    {        try        {            var fileInfo = new FileInfo(_filePath);            if (fileInfo.Exists && (fileInfo.Length / 1024 >= _maxSizeInKiloBytes))            {                CreateCopyOfCurrentLogFile(_filePath);            }            using (var fileStream = new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.Read))            {                using (var writer = new StreamWriter(fileStream))                {                    foreach (var batchEntry in batchEntries)                    {                        var message = FormatLogEvent(batchEntry.Log, batchEntry.Message, batchEntry.LogEvent, batchEntry.ExtraData);                        writer.WriteLine(message);                    }                }            }        }        catch (Exception)        {            // Swallow        }    }    private void CreateCopyOfCurrentLogFile(string filePath)    {        for (int i = 1; i < 999; i++)        {            var possibleFilePath = string.Format("{0}.{1:000}", filePath, i);            if (!File.Exists(possibleFilePath))            {                File.Move(filePath, possibleFilePath);            }        }    }}
5. integrate third-party log Functions

Logs in catel do not write any output by default. This gives developers the freedom to use any final Log Mechanism to process logs. For example, catel can easily use log4net or nlog for integration. Generally, the following steps need to be performed to integrate logs.

1. Create your own or use loglistenerbase to create a custom iloglistener

2. Use logmanager. addlistener to register it.

  1. 5.1 integrate the log4net Method

The following example provides an iloglistener for log4net, but some additional log libraries can be used.

5.1.1 create listener

Create a new class by inheriting loglistenerbase:

 

public class Log4netListener : LogListenerBase{    protected override void Debug(ILog log, string message, object extraData)    {        var finalLog = log4net.LogManager.GetLogger(log.TargetType);        finalLog.Debug(message);    }     protected override void Info(ILog log, string message, object extraData)    {        var finalLog = log4net.LogManager.GetLogger(log.TargetType);        finalLog.Info(message);    }     protected override void Warning(ILog log, string message, object extraData)    {        var finalLog = log4net.LogManager.GetLogger(log.TargetType);        finalLog.Warn(message);    }     protected override void Error(ILog log, string message, object extraData)    {        var finalLog = log4net.LogManager.GetLogger(log.TargetType);        finalLog.Error(message);    }}

 

5.1.2 register a listener

Finally, register the listener.

LogManager.AddListener(new Log4netListener());
5.1.3 configure log4net

Note: This is just a simple configuration. Check the log4net documentation to view all the options:

1. Add log4net references.

2. Add [Assembly: log4net. config. xmlconfigurator (watch = true)] to assemblyinfo. CS.

3. Configure the actual log4net data in APP. config.

 

 

5.2 inherit the nlog Method

The following example provides an iloglistener for nlog, but some additional log libraries can be used.

5.2.1 create listener

Create a new class by inheriting loglistenerbase:

 

public class NLogListener : LogListenerBase{    protected override void Debug(ILog log, string message, object extraData)    {        var finalLog = NLog.LogManager.GetLogger(log.TargetType.ToString());        finalLog.Debug(message);    }     protected override void Info(ILog log, string message, object extraData)    {        var finalLog = NLog.LogManager.GetLogger(log.TargetType.ToString());        finalLog.Info(message);    }     protected override void Warning(ILog log, string message, object extraData)    {        var finalLog = NLog.LogManager.GetLogger(log.TargetType.ToString());        finalLog.Warn(message);    }     protected override void Error(ILog log, string message, object extraData)    {        var finalLog = NLog.LogManager.GetLogger(log.TargetType.ToString());        finalLog.Error(message);    }}
5.1.2 register a listener

Finally, register the listener.

LogManager.AddListener(new NLogListener());
 

 

 

 

6. Write logs to the disk.

Catel also supports lightweight listeners to allow other external libraries, create a listener, and create a new class to inherit from iloglistener. Next, register it to logmanager.

Iloglistener has an independent method for each logevent, but there is also a shared method to call. For example, if the debug information is written to the log, both the write and debug methods are called on the iloglistener.

Note: You can refer to the previous log updates for the example of writing data to disks in batches.

Note: catel already contains a fileloglistener and does not need to be rewritten. It is easy to understand as an example.

6.1 create a listener

You can write a new class that inherits from loglistenerbase.

public class FileLogListener : LogListenerBase{    private readonly TextWriter _textWriter;     public FileLogListener(string fileName)    {        Argument.IsNotNullOrWhitespace("fileName", fileName);        FileName = fileName;         _textWriter = new StreamWriter(fileName, true);    }     public string FileName { get; private set; }     public override void Write(ILog log, string message, LogEvent logEvent)    {        _textWriter.WriteLine(message);    }}

6.2 register a listener

Finally, register this listener as important.

LogManager.AddListener(new FileLogListener("<log_file_path>"));

 

 

7. Create a listener through the configuration file

 

You can use the configuration file to initialize loglistener from 3.8. The following is an example.

 

 

<configSections>    <sectionGroup name="catel">        <section name="logging" type="Catel.Logging.LoggingConfigurationSection, Catel.Core" />    </sectionGroup></configSections> <catel>    <logging>        <listeners>            <listener type="Catel.Logging.FileLogListener" FilePath="CatelLogging.txt" IgnoreCatelLogging="true" IsDebugEnabled="false" IsInfoEnabled="true" IsWarningEnabled="true" IsErrorEnabled="true"/>        </listeners>    </logging></catel>

The preceding logging node needs to protect an unlimited number of listeners. each listener must provide at least a namespace of the type.

<listener type="Catel.Logging.FileLogListener" />

Other attributes are customized. Users can customize each added listener. The following is the configuration for registering fileloglistener.

<listener type="Catel.Logging.FileLogListener" FilePath="CatelLogging.txt" IgnoreCatelLogging="true"          IsDebugEnabled="false" IsInfoEnabled="true" IsWarningEnabled="true" IsErrorEnabled="true"/>

Iloglistenr attributes (Isdebugenabled,Isinfoenabled,IswarningenabledAndIserrorenabled) Is effective for all listeners. Other options depend on the specific listener class, which can improve the runtime flexibility.

Catel help manual-catel. Core (6): Log Management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.