怎么为网站写日志(Log4Net)

1 添加log4net dll的引用

2 在web.config中添加如下代码

①放在<configSections>节点下面

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


②放在<configSections/>下面

 1 <log4net>
 2     <!-- Define some output appenders -->
 3     <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
 4       <file value="Log.txt"/>
 5       <appendToFile value="true"/>
 6       <maxSizeRollBackups value="10"/>
 7       <maximumFileSize value="1024KB"/>
 8       <rollingStyle value="Size"/>
 9       <staticLogFileName value="true"/>
10       <layout type="log4net.Layout.PatternLayout">
11         <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
12       </layout>
13     </appender>
14     <root>
15       <level value="DEBUG"/>
16       <appender-ref ref="RollingLogFileAppender"/>
17     </root>
18   </log4net>

3 在Global.asax页面中的Application_Start中 添加
log4net.Config.XmlConfigurator.Configure();

4 在需要输出日志的class中使用

 public partial class TestLog4Net : System.Web.UI.Page
    {
        private static ILog logger = LogManager.GetLogger(typeof(TestLog4Net));
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection conn = new SqlConnection("错的的连接字符串!");
                conn.Open();
            }
            catch (Exception ex)
            {
                logger.Error("连接数据库失败", ex);
            }
        }
    }

 

你可能感兴趣的:(log)