Full parsing of log functions in the ABP Framework _ Practical Tips

Source: Internet
Author: User
Tags log4net

asp.net boilerplate uses the castle Windsor ' s logging facility logging tool, and can use a different log class library, such as: Log4net, Nlog, Serilog ... Wait a minute. For all log class libraries, Castle provides a common interface to implement, we can easily handle a variety of special log libraries, and when the business needs, it is easy to replace the log components.

Translator's note: What is Castle: Castle is an open source project for the. NET platform, from the data Access framework ORM to the IOC container, to the MVC framework of the web layer, AOP, which basically includes everything in the entire development process. asp.net boilerplate's IOC container is achieved through castle.

Log4net is one of the most popular log library components under ASP.net, asp.net boilerplate templates also use log4net Log library components, but we do this only with a single line of key code log4net Dependency injection (specifically in the following configuration file), so if you want to replace it with your own log component, it's also easy.

Get Log Logger Logger

Regardless of which log library component you choose, logging through the code is the same. (Here, the Castle ' s Universal ILogger interface is really awesome.)

The following goes to the point: (Translator Note: The following code is the ABP framework of Castle.core source analysis and implementation)

1, first of all, we have to deal with the Logger object logger, asp.net boilerplate framework using dependency Injection Dependency Injection technology, we can easily use dependency injection to generate logger object logger.

Let's take a look at how ASP.net boilerplate implements the logging feature:

Using Castle.Core.Logging; 1: The namespace of the import log, Castle.Core.Logging public

class Taskappservice:itaskappservice
{ 
  //2: Gets the Logger object through dependency injection.
  Here we first define a ILogger type of public attribute logger, which is the object we use to record the log. After creating the Taskappservice object (the task defined in our application), it is implemented by means of property injection. Public
  ILogger Logger {get; set;}

  Public Taskappservice ()
  { 
   //3: If there is no logger, return the logger to an empty instance and not write a log. This is the best way to implement dependency injection,
   //  If you do not define this empty logger, an exception is generated when we get the object reference and instantiate it.
   //  This ensures that the object is not empty. So, in other words, without setting the logger, the log is not logged and a null object is returned.
   //  Nulllogger objects actually everything wood has, empty. In so doing, we can guarantee that our defined classes work correctly when instantiated.
   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 the log is written, we can view the log file, as in the following format:

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

using logger through base classes

The ASP.net boilerplate framework provides the base class for MVC controllers, Web API controllers, and application service classes (its own defined controller and application services, Must inherit the base class of ASP.net boilerplate, in other words, when you customize the Web API controllers, MVC controllers,application service classes inherit asp.net Boilerplate framework corresponding to the base class, you can use the logger directly.

public class Homecontroller:simpletasksystemcontrollerbase 
{public 
  actionresult Index () 
  { 
   Logger.debug ("A sample Log message ..."); 
   return View (); 
  } 
 

Description: Simpletasksystemcontrollerbase This base class controller is our own definition of the base class controller, he must inherit from Abpcontroller.

This enables the logger to work correctly. Of course, you can also implement your own base class, so that you can also not use dependency injection.

Configuration

If you build your project on the official web through asp.net boilerplate templates, all log4net configurations are automatically generated.

The default configuration format is as follows:

    • Log level: Logging levels, with Debug, INFO, WARN, ERROR or FATAL5.
    • Date and time: Log record times.
    • Thread #: The number of threads per line of log writes.
    • Logger Name: The names of the loggers, usually in the case of the class name.
    • Log text: The contents of the journal that you write.

Configuration files: Log4net.config are 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= "ten"/> <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 log library components, you can write a variety of logs, such as writing to TXT file, write to the database and so on. You can set the minimum log level, just like the one above for nhibernate configuration. Different loggers write different logs, and so on.

The concrete usage everybody can refer to: http://logging.apache.org/log4net/release/config-examples.html

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

A few lines of code call log4net This logging component, the Log4net library in the project is in the NuGet package package, and you can change to another log component library, but the code doesn't have to make any changes. Because our framework is to implement the logger through dependency injection!

Client side (clients)

Last but not the worse, you can also call the logger at the client. On the client side, the ASP.net boilerplate framework has a corresponding JavaScript log API, which means you can record the browser's log and implement the following code:

Abp.log.warn (' A sample log message ... '); 

Attached: Client JavaScript API, here to illustrate, you can use Console.log on the client output log, but this API does not necessarily support all browsers, but also may cause your script to appear abnormal, you can use our API, our security, 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 Logs
ABP provides the infrastructure to automatically record logs for applications, which can record caller and parameter information for the method you are invoking. Essentially, the storage area contains:

    • Tenant ID (The associated tenant ID),
    • User ID (the request ID),
    • Server name (the requested service name "invokes a method-corresponding class"),
    • Method name (invoking the name of the methods),
    • Parameters (the parameter of the method "JSON format"),
    • Execution time (execution times),
    • Duration (execution takes time "is usually milliseconds"),
    • IP address (client IP),
    • Computer name (client name),
    • Exception (Exception "If the method throws an exception"), and other information.

With this information, we can not only know who did the operation, but also estimate the performance of the application and the exceptions thrown. Even more, you can get statistics about the usage of the application.

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

Note: About the Iauditingstore interface

The audit system uses the Iauditingstore interface to hold audit information. 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 yourself, the Simplelogauditingstore class can be used directly, and it is implemented by writing audit information to the log.

Configuration:
You can configure auditing using Configuration.auditing properties in your module initialization method (Preinitialize), and the auditing property is enabled by default (that is, true). You can disable it as shown in the following illustration:

public class Mymodule:abpmodule
{public
  override void Preinitialize ()
  {
    Configuration.Auditing.IsEnabled = false;
  }

  //...
}

The following are the properties of the audit configuration:

IsEnabled: Used to set up full enable or disable auditing systems. Default value: True.
Isenabledforanonymoususers: If set to Ture, the audit log of the user who did not log in will also be saved. Default value: False.
Mvccontrollers: Use audit log isenabled in asp.net MVC controller
: Enable (true) or disable (false) audit log in asp.net mvc. Default value: True.
Isenabledforchildactions: Enable (true) or disable (false) audit logs for the MVC actions. Default value: False.
Selectors: Choose to use a different class to handle the storage of the audit log.

As you can see, the audit system alone provides an audit configuration for the MVC controller that allows it to be used in a different way.

Selectors is an assertion (inferred type) selector list that is used to select the way to save an audit log. Each selector contains a unique name and an assertion. The default selector in the assertion list, using the Application service class. As shown in the following illustration:

CONFIGURATION.AUDITING.SELECTORS.ADD (
  new Namedtypeselector (
    "abp.applicationservices",
    type => typeof (Iapplicationservice). IsAssignableFrom (type)
  )
);

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

To enable and disable an audit log through properties:
When you use configuration items to configure the assertion selector, you can enable and disable the audit system by marking the audited and disableauditing attributes to a single class or a single method. For example:

[Audited]
public class MyClass
{public
  void MyMethod1 (int a)
  {
    //...
  }

  [Disableauditing]
  public void MyMethod2 (string b)
  {
    //...
  }

  public void MyMethod3 (int a, int b)
  {
    //...
  }
}

The above Liezi, the MyClass class in addition to MYMETHOD2 clear Mark does not need to audit, other methods will be audited. The audited feature can help you to save only the methods of auditing the log, and the audit log.

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.