log4net 使用总结- (3)在ASP.NET MVC 中使用
把输出到sqlserver数据库中。
输出到数据库中和文件中类似,具体配步骤如下
第一步、创建数据库
CREATE TABLE [dbo].[Log] ( [Id] [int] IDENTITY (1, 1) NOT NULL, [Date] [datetime] NOT NULL, [Thread] [varchar] (255) NOT NULL, [Level] [varchar] (50) NOT NULL, [Logger] [varchar] (255) NOT NULL, [Message] [varchar] (4000) NOT NULL, [Exception] [varchar] (2000) NULL )
第二步、配置log4net.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <!--定义输出到数据库中--> <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <bufferSize value="1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="data source=[XXX];initial catalog=[XXX];integrated security=false;persist security info=True;User ID=[XXX];Password=[XXX]" /> <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" /> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="2000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> </appender> <root> <!--OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL--> <level value="ALL"/> <!--数据库形式记录日志--> <appender-ref ref="AdoNetAppender"/> </root> </log4net> </configuration>
第三步、配置properties
在站点properties 下找到AssemblyInfo增加
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
第四步、在控制台写测试一样work
public class HomeController : Controller { log4net.ILog log = log4net.LogManager.GetLogger(typeof(HomeController)); public ActionResult Index() { log.Info("Home->Index test"); return View(); } }
个人签名:天行健,君子以自强不息