Fully parses the log function in the ABP framework, and parses the logs in the abp framework.

Source: Internet
Author: User
Tags log4net

Fully parses the log function in the ABP framework, and parses the logs in the abp framework.

ASP. NET Boilerplate uses the Castle Windsor's logging facility logging tool and can use different log libraries, such as Log4Net, NLog, Serilog... and so on. For all the log class libraries, Castle provides a common interface for implementation. We can easily process a variety of special logstores, and when the business needs, it is easy to replace the log component.

Note: What is Castle? Castle is. an open-source project of the. NET platform, from the data access framework ORM to the IOC container, to the MVC Framework and AOP at the WEB layer, basically covers everything in the entire development process. The ioc container of ASP. NET Boilerplate is implemented by Castle.

Log4Net is the most popular logstore component in asp.net, ASP. the NET Boilerplate template also uses the Log4Net logstore component. However, here we only use a line of key code to implement Log4Net dependency injection (the specific description is shown in the following configuration file, it is easy if you want to replace it with your own log component.

Obtain logger

No matter which logstore component you choose, it is the same for logging through code. (In this case, the Castle's general ILogger interface is awesome ).

(Note: The following code is the source code analysis and implementation of the Castle. Core of the abp framework)

1. First, we need to process the logger, ASP. the NET Boilerplate framework uses the dependency injection technology. We can easily use dependency injection to generate a logger object.

Next, let's take a look at how ASP. NET Boilerplate implements the logging function:

Using Castle. Core. Logging; // 1: The namespace for importing logs. Castle. Core. Loggingpublic class TaskAppService: ITaskAppService {// 2: obtains the Logging object through dependency injection. Here, we first define a public attribute Logger of the ILogger type. This object is the object we use to record logs. After a TaskAppService object is created (a task defined in our application), it is implemented through property injection. Public ILogger Logger {get; set;} public TaskAppService () {// 3: If no Logger exists, the Logger returns an empty instance without writing logs. This is the best way to implement dependency injection. // if you do not define this empty logger, an exception will occur when we get the object reference and instantiate it. // This ensures that the object is not empty. Therefore, in other words, if a logger is not set, logs are not recorded and a null object is returned. // The NullLogger object is actually empty. In this way, we can ensure that the classes we define work normally during instantiation. Logger = NullLogger. instance;} public void CreateTask (CreateTaskInput input) {// 4: Write log Logger. info ("Creating a new task with description:" + input. description); // TODO: save task to database ...}}

After writing logs, we can view the log file, as shown in the following format:

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

ASP. NET Boilerplate framework provides the base classes of MVC Controllers, Web API Controllers, and Application service classes (the controller and Application service defined by the user must inherit ASP. NET Boilerplate base class. In other words, when your custom Web API controllers, mvc controllers, Application service classes all inherit ASP. NET Boilerplate framework corresponds to the base class, you can directly use the logger ).

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

Note: SimpleTaskSystemControllerBase is a base class controller defined by us. It must inherit from AbpController.

In this way, the log recorder can work normally. Of course, you can also implement your own base class, so that you do not need to use dependency injection.

Configuration

If you use ASP. NET Boilerplate templates on the official website to generate your project, all Log4Net configurations are automatically generated.

The default configuration format is as follows:

  • Log level: Log record level, including DEBUG, INFO, WARN, ERROR or fatal5.
  • Date and time: the log record time.
  • Thread number: the Thread number used to write logs per line.
  • Logger name: the name of the Logger, usually the class name.
  • Log text: the Log Content you write.

Configuration File: log4net. config is generally under the project's web directory.

<?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 very powerful and easy-to-use logstore component. You can write various logs, such as txt files and databases. You can set the minimum Log Level, just like the above configuration for nhib.pdf. Different recorders write different logs.

Specific usage you can refer to: http://logging.apache.org/log4net/release/config-examples.html

Finally, define the Log4Net configuration file in the project's Global. asax 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);  }}

Several lines of code call the Log4Net logging component. The Log4Net library in the project is in the nuget package. You can also replace it with other log component libraries, but the Code does not need to be changed. Because our framework implements logger through dependency injection!

Client side)

Finally, you can call the logger on the client. On the client side, the ASP. NET Boilerplate framework has the corresponding javascript log API, which means you can record the browser log. The implementation code is as follows:

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

Attached: the client's javascript api. Here, you can use the console. logs are output on the client, but this API does not necessarily support all browsers. It may also cause exceptions in your script. You can use our api, which is safe, you can even overload or extend these Apis.

abp.log.debug('...');abp.log.info('...');abp.log.warn('...');abp.log.error('...'); abp.log.fatal('...');


Audit trail log
ABP provides an infrastructure that automatically records logs for application interactions. It records Caller information and parameter information of the method you call. Basically, the storage areas include:

  • Tenant id (tenant Id ),
  • User id (request user id ),
  • Server name (requested service name [class corresponding to the call method ]),
  • Method name (call method name ),
  • Parameters (method parameter [JSON format ]),
  • Execution time (execution time ),
  • Duration (execution time (usually in milliseconds ]),
  • IP address (Client IP address ),
  • Computer name (client name ),
  • Exception (if the method throws an exception) and other information.

With this information, we can not only know who has performed the operation, but also estimate the application performance and thrown exceptions. For more information, see Application Usage Statistics.

The audit system uses the IAbpSession interface to obtain the current user ID and tenant ID.

Note: IAuditingStore APIs

The audit system uses the IAuditingStore interface to save audit information. The module-zero project is the complete implementation of this interface. Of course, you can also implement this interface in your own way. If you do not want to implement this interface by yourself, the SimpleLogAuditingStore class can be used directly. It is implemented by writing audit information into logs.

Configuration:
You can use the Configuration. Auditing attribute in your module initialization method (PreInitialize) to configure audit. The Auditing attribute is enabled (that is, true) by default ). You can disable it, as shown in:

public class MyModule : AbpModule{  public override void PreInitialize()  {    Configuration.Auditing.IsEnabled = false;  }  //...}

The attributes of Audit Configuration are as follows:

IsEnabled: used to set the audit system to be fully enabled or disabled. Default Value: true. IsEnabledForAnonymousUsers: if it is set to true, audit logs of Unlogged users will also be saved. Default Value: false. mvcControllers: In ASP. net mvc controller using audit log IsEnabled: In ASP. net mvc enable (true) or disable (false) audit log. default Value: true. isEnabledForChildActions: enables (true) or disables (false) audit logs for MVC actions. default Value: false. selectors: select other classes to store audit logs.

As you can see, the audit system provides an audit configuration for the mvc Controller so that it can be used in different ways.

Selectors is a list of assertion (inference type) Selectors used to select the method to save audit logs. Each selector contains a unique name and an asserted. The default selector in the assertion list, which uses the application service class. As shown in:

Configuration.Auditing.Selectors.Add(  new NamedTypeSelector(    "Abp.ApplicationServices",    type => typeof (IApplicationService).IsAssignableFrom(type)  ));

You can add your own assertion selector in your module initialization method (PreInitialize. Similarly, if you do not like to use the application service to save audit logs, you can also remove the asserted selector by name, this is why the name of the assertion selector must be unique (you can also find the selector to remove it through the Linq method ).

Enable and disable audit logs using attributes:
When you use configuration items to configure the assertion selector, you can enable and disable the audit system by marking it to a single class or a single method using the Audited and DisableAuditing features. For example:

[Audited]public class MyClass{  public void MyMethod1(int a)  {    //...  }  [DisableAuditing]  public void MyMethod2(string b)  {    //...  }  public void MyMethod3(int a, int b)  {    //...  }}

In the above column, except for the explicit mark of MyMethod2 in MyClass, other methods will be audited. The Audited feature helps you save audit logs only by saving audit logs.



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.