& Lt; ABP framework & gt; logs, and abp framework logs

Source: Internet
Author: User
Tags log4net

<ABP framework> logs and the abp framework logs

Document directory

 

Content of this section:

  • Server
    • Obtain Logger (recorder)
    • Logger base class
    • Configuration
    • Abp. Castle. Log4Net package
  • Client

 

Server

Can work with different logginh (log) Class Libraries: Log4Net, NLog, and Serilog. Castle provides a public interface for all Logger libraries, so it is independent of the logging library and can easily replace logging when necessary.

Log4Net is the most popular Logging library. The ABP template works with the properly configured Log4Net, but it is only a single-line mode dependency (view the "configuration" topic ), so you can replace it with your favorite logstore.

 

Obtain Logger (recorder)

No matter which logging library you use, the log writing code is the same (thanks to Castle's public ILogger interface ).

First, we should obtain a Logger. Because the large number of resource-level (ABP) Dependency injection is used, we can use the attribute injection (or constructor injection) mode to inject a Logger object. Let's take a look at the sample classes for writing a line of logs:

using Castle.Core.Logging; //1: Import Logging namespacepublic class TaskAppService : ITaskAppService{        //2: Getting a logger using property injection    public ILogger Logger { get; set; }    public TaskAppService()    {        //3: Do not write logs if no Logger supplied.        Logger = NullLogger.Instance;    }    public void CreateTask(CreateTaskInput input)    {        //4: Write logs        Logger.Info("Creating a new task with description: " + input.Description);        //TODO: save task to database...    }}

First, we reference the namespace of Castle's ILogger interface.

In fact, we define a public ILogger object named Logger. this object will write logs, and the dependency injection system will set (inject) This attribute after the TaskAppService object is created, this is the famous property injection mode.

Third, set Logger to NullLogger. Instance. The system can work without this line of code, but this is the best practice of the property injection mode. If this Logger is not available, an exception "Object Reference..." will be received when you use it. This is to ensure that it is not empty, so if this Logger is not set, it is NullLogger. This is the famous Null Object Mode. NullLogger essentially does nothing and does not write any logs. Therefore, our class can work regardless of whether there is a real logger.

Finally, we use the info level to write a text log. There are several different levels (view the "configuration" topic ).

If we call the CreateTask method and check the log file, we can see a line similar to the following:

INFO  2014-07-13 13:40:23,360 [8    ] SimpleTaskSystem.Tasks.TaskAppService    - Creating a new task with description: Remember to drink milk before sleeping!

 

Logger base class

ABP provides a base class for Mvc controllers, Web Api controllers, and Application Service classes. They declare a Logger attribute, so you can directly use this Logger to write logs without injection. For example:

public class HomeController : SimpleTaskSystemControllerBase{    public ActionResult Index()    {         Logger.Debug("A sample log message...");        return View();    }}

Note: SimpleTaskSystemControllerBase is the base class that our application inherits from AbpController. Therefore, Logger can be used directly. Similarly, you can write a public base class for your other classes, and then you don't have to inject Logger every time.

 

Configuration

All configurations of Log4Net have been completed for the application created from the ABP template.

The default log format is as follows (each line)

  • Log Level: DEBUG, INFO, WARN, ERROR, or FATAL.
  • Date and time: the date and time when the log is written.
  • Thread number: the thread Number of the log writing thread.
  • Logger name: Generally the class name used to write logs.
  • Log text: You actually write the log text.

They are defined in the log4net. config file of the application, as follows:

<?xml version="1.0" encoding="utf-8" ?><log4net>  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >    <file value="Logs/Logs.txt" />    <appendToFile value="true" />    <rollingStyle value="Size" />    <maxSizeRollBackups value="10" />    <maximumFileSize value="10000KB" />    <staticLogFileName value="true" />    <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />    </layout>  </appender>  <root>    <appender-ref ref="RollingFileAppender" />    <level value="DEBUG" />  </root>  <logger name="NHibernate">    <level value="WARN" />  </logger></log4net>

Log4net is a highly configurable and powerful logging library. You can write logs in different formats to different media (text files, databases ...), you can set the minimum log level. You can write different logs to different log files. When the log file reaches the specified size, it will automatically back up and create a new log file (in this configuration, the rollback file is configured in kilobytes per file) and so on. read its own Configuration documentation for more information.

Finally, in the Global. asax file, we declare that log4net should be used in the Log4Net. config file:

public class MvcApplication : AbpWebApplication{    protected override void Application_Start(object sender, EventArgs e)    {        IocManager.Instance.IocContainer.AddFacility<LoggingFacility>(f => f.UseLog4Net().WithConfig("log4net.config"));        base.Application_Start(sender, e);    }}

This is the only line of code that depends on log4net, and the Web project only depends on the nuget package of the log4net class. Therefore, you can easily switch to another database without changing other log codes.

 

Abp. Castle. Log4Net package

The ABP uses the Castle logging tool, which does not directly rely on log4net, as described above. However, there is a Log4Net integration problem with Castle. It does not support the latest version of log4new. We create an nuget package named ABC. Castle. Log4Net to solve this problem. After adding this package to our solution, all we need to do is modify the code in the application startup Code as follows:

public class MvcApplication : AbpWebApplication{    protected override void Application_Start(object sender, EventArgs e)    {        IocManager.Instance.IocContainer.AddFacility<LoggingFacility>(f => f.UseAbpLog4Net().WithConfig("log4net.config"));        base.Application_Start(sender, e);    }}

The only difference is that we use the "UseAbpLog4Net ()" method (defined in the ABC. Castle. Logging. Log4Net namespace) to replace "UseLog4Net ()". When we use the ABC. Castle. Log4Net package, we no longer need the Castle. Windsor-log4net and Castle. Core-log4net packages.

 

Client

The ABP defines a simple Javascript logging Api for the client, which writes logs on the console of the browser by default. The sample code is as follows:

abp.log.warn('a sample log message...');

For more information, see the logging API documentation.

 

Related Article

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.