Detailed ABP The basic configuration of log management and settings management in the framework _asp programming

Source: Internet
Author: User
Tags change settings log4net

Log Management
Server side (servers side)
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 is wood there, 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 ...} 
} 

Copy Code code as follows:

INFO 2014-07-13 13:40:23,360 [8] simpletasksystem.tasks.taskappservice-creating a new task with Description:remember to Drink milk before sleeping!

After the log is written, we can view the log file, as in the following format:

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 Number: The thread numbers for each line of log writes.
Logger Name: The names of the loggers, usually in the case of the class name.
Log text: The log content 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 (' ... ');

Settings Management
Introduce
each application needs to store some settings and use these settings somewhere in the application. The ABP Framework provides a powerful infrastructure for storing/capturing application, tenant, and user-level configurations on either the server or client settings.

Settings are typically stored in a database (or another source), represented by a structure corresponding to a name-value (Name-value) string. We can store the non string value as a string value.

Note: About the Isettingstore interface

The Isettingstore interface must be implemented in order to use settings management. You can use your own way to achieve it, in the Module-zero project has a complete implementation can refer to.

Defining settings
You must define the settings before you use them. The ABP framework is a modular design, so different modules can have different settings. In order to define the module's own settings, each module should create a derived class that inherits from Settingprovider. The settings provider example looks like this:

public class Mysettingprovider:settingprovider
{public
 override ienumerable<settingdefinition> Getsettingdefinitions (Settingdefinitionprovidercontext context)
 {return
  new[]
    {
     new Settingdefinition ("
      smtpserveraddress",
      "127.0.0.1"
      ),

     new Settingdefinition (
      " Passiveuserscannotlogin ",
      " true ",
      scopes:SettingScopes.Application | Settingscopes.tenant
      ),

     new Settingdefinition (
      "sitecolorpreference",
      "red",
      scopes: Settingscopes.user,
      isvisibletoclients:true
      )
    }
 

The Getsettingdefinitions method returns the Settingdefinition object. The constructor for the Settingdefinition class has the following parameters:

name (required): Must have a system-wide unique name. A better approach is to define the string constants to set name.
Default value: Sets a default value. This value can be either null or an empty string.
scopes: Defines the scope of the setting (see below).
Display Name: A localizable string for displaying the name of the setting in the UI later.
Description: A localizable string that can be used to display a description of the settings in the UI later.
Group: Can be used to set up groups. This is only UI usage and is not used for setup management.
isvisibletoclients: Setting to True will make the settings available to the client.
After creating the provisioning provider (Settingprovider), we should register our modules in the pre-initialization (Preintialize) method:

Configuration.settings.providers.add<mysettingprovider> (); The provisioning provider automatically registers dependency injection. Therefore, the settings provider can inject any dependency, such as a repository, to generate some other source of the settings definition.

Set Range
There are three settings ranges (or levels) defined in the Settingscopes enumeration:

Application: Application-scoped settings are used for user/tenant independent settings. For example, we can define a setting named "Smtpserveraddress", and when sending an e-mail message, get the IP address of the server. If this setting has a single value (not based on user change), then we can define it as an application scope.
Tenant: If the application is multi-tenant, we can define the tenant-specific settings.
User: We can use the user-scoped settings to store/Get set values for each user.
The Settingscopes enumeration has the flags attribute, so we can define a setting with multiple scopes.

The settings range is layered. For example, if we define a set range of "application | Tenant | User and attempts to get the value of the current setting;

• We get the value of a particular user, if it defines (overrides) user.
• If not, we get a specific tenant value if it defines (overrides) tenant.
• If not, we get the value of the application if it defines application.
• If not, we get the default value.
The default value can be null or an empty string. If possible, it is recommended that you provide a default value for the setting.

Get Set Value
after defining the settings, we can get the current value of the server and the client.

(1) server-side (side)
Isettingmanager is used to perform setup operations. We can inject and use it anywhere in the application. Isettingmanager defines a lot of ways to get set values.

The most commonly used method is Getsettingvalue (or Getsettingvalueasync for asynchronous invocation). It returns the current set of values based on default values, applications, tenants, and user settings, as described in the previous section of the set scope. Example:

Getting a Boolean value (Async call)
var value1 = await settingmanager.getsettingvalueasync<bool> (" Passiveuserscannotlogin ");
Getting a String value (Sync call)
var value2 = settingmanager.getsettingvalue ("smtpserveraddress"); 

Getsettingvalue has generic and asynchronous versions, as shown above. There are also ways to get a list of settings or all set values for a particular tenant or user.

Because Isettingmanager is widely used, some specific base classes (such as Applicationservice, Domainservice, and Abpcontroller) have a property named Settingmanager. If we inherit from these classes, we don't have to inject it explicitly.

(2) Client
If you set Isvisibletoclients to True when you define a setting, you can use JavaScript on the client to get its current value. abp.setting namespaces define the functions and objects that are required. Example:

var currentcolor = abp.setting.get ("sitecolorpreference"); There are also methods such as GetInt and Getboolean. You can use the Abp.setting.values object to get all the values. Note that if you change the settings on the server side, the client will not know about the change unless the page is refreshed or the page is reloaded in some way or manually updated by code.

Change settings
Isettingmanager defines Changesettingforapplicationasync,changesettingfortenantasync and ChangeSettingForUserAsync. Method (and synchronized version) to change the settings for the application, the tenant, and the user respectively.

About caching
caching is managed on the server side, so we should not change the values of the settings directly using the repository or database update statements.

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.