How to do the log under ASP. NET MVC

Source: Internet
Author: User
Tags log4net

Items are available in ASP. NET MVC under the log and write to the database inside the needs, and then search for information on the Internet, found a variety of solutions, put other people's things on their own machine, found that the problem can not be solved, for nearly two days, finally solved the problem, in this record down.

First, solve the problem written in the general file:

Solution steps:

1. First download a log4net.dll. And put it in your reference.

2. Add a line at the bottom of the AssemblyInfo.cs

[Assembly:log4net. Config.xmlconfigurator (configfile = "Log4net.config", Watch = True)], Log4net.config here is what you're going to

Place some of the configuration. This file is placed under the root directory of the project. Content is:

<?xml version= "1.0"?> <configuration> <configSections> <section name= "Log4net" System.Configuration.IgnoreHandlerSection "/> </configSections> <log4net> <appender name=" console "Type=" log4net. Appender.consoleappender "></appender> <root> <level value=" WARN/> <appender-ref ref= Logfileappender "/> </root> <logger name=" Test "> <level value=" DEBUG "/> </logger> < Appender name= "Logfileappender" type= "log4net". Appender.fileappender "> <param name=" File "value=" d:/documents and Settings/e518731/log.txt "/> <param Name= "Appendtofile" value= true "/> <layout type=" log4net. Layout.patternlayout "> <param name=" Header "value=" [header]/r/n "/> <param] name=" Footer "value=" [Footer]/ r/n "/> <param name=" Conversionpattern "value="%d [%t]%-5p%c [%x]-%m%n "/> </layout> </appender> &L T;/log4net> </configuration>

The code in 3.Controller is written like this:

public class Homecontroller:controller {log4net. ILog log = log4net. Logmanager.getlogger ("Test"); Public ActionResult Index () {log. Error ("haha"); return View (); } }

So you can write log into a file.

Second, solve the problem of writing custom log to the database

1. First download a log4net.dll. And put it in your reference.

2. Add the following line to the Global.asax Application_Start method

Log4net. Config.XmlConfigurator.Configure ();

3. Create a custom Log object

public class Logcontent {public string contents, public int userId;}

4. In the configsections of Web.config, add the following section

<section name= "log4net" type= "log4net". Config.log4netconfigurationsectionhandler, log4net "/>

5. Outside the configsections section, add the following

<log4net> <appender name= "Adonetappender" type= "log4net". Appender.adonetappender "> <buffersize value=" 0 "/> <connectiontype value=" System.Data.SqlClient.SqlConnection, System.Data, version=2.0.0.0, Culture=neutral, publickeytoken= b77a5c561934e089 "/> <connectionstring value=" server=ch71dtbfxt12x/sqlexpress; Uid=sa; Pwd=password; Database=atms "/> <commandtext value=" INSERT into Logs ([createdat],[contents],[userid],[severity]) VALUES (@log _date, @contents, @userId, @level) "/> <parameter> <parametername value=" @log_date "/> <dbtype value=" DateTime "/> <layout type=" log4net. Layout.rawtimestamplayout "/> </parameter> <parameter> <parametername value=" @contents "/> < DbType value= "String"/> <size value= "256"/> <layout type= "ATMS". ATMSWeb.Log4Net.MyLayout "> <conversionpattern value="%contents "/> </layout> </parameter> < parameter> <parametername value= "@userId"/> <dBtype value= "Int32"/> <layout type= "ATMS". ATMSWeb.Log4Net.MyLayout "> <conversionpattern value="%userid "/> </layout> </parameter> < parameter> <parametername value= "@level"/> <dbtype value= "String"/> <size value= "256"/> < Layout type= "log4net. Layout.patternlayout "value="%level "/> </parameter> </appender> <root> <level value=" DEBUG "/ > <appender-ref ref= "adonetappender"/> </root> </log4net>

6. Create a new file that contains the following:

Namespace ATMS. atmsweb.log4net {public class Mylayout:patternlayout {public Mylayout () {this. Addconverter ("Contents", typeof (Contentspatternconverter)); This. Addconverter ("UserId", typeof (Useridpatternconverter)); } public class Contentspatternconverter:patternlayoutconverter {override protected void Convert (TextWriter writer, Lo Ggingevent loggingevent) {logcontent logmessage = loggingevent.messageobject as logcontent; if (logMessage!= null) write R.write (logmessage.contents); } public class Useridpatternconverter:patternlayoutconverter {override protected void Convert (TextWriter writer, Logg Ingevent loggingevent) {logcontent logmessage = loggingevent.messageobject as logcontent; if (logMessage!= null) writer. Write (Logmessage.userid); } } }

7. When the diary, the following wording:

private static readonly ILog log = Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType); Log. Error (new Logcontent {contents= "ss", userid=4});

Then you can write the date to the database table.

Some of the specific configurations may vary from person to person, such as the configuration of database connection strings. What do not understand, welcome to leave a message

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.