生成Log日志文件.NE

首先创建一个log4net.config的文件,在文件里面设置如下:

View Code
<?xml version="1.0" encoding="utf-8"?>

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

    <logger name="LogSystem">
      <level value="ALL"/>
      <!--<appender-ref ref="AdoNetAppender_SqlServer" />-->
      <appender-ref ref="rollingFile" />
    </logger>

    <!--<root>
            <level value="OFF"/>
            <appender-ref ref="AdoNetAppender_SqlServer"/>
        </root>-->

    <!--记录到文件方式-->
    <appender name="rollingFile" type="log4net.Appender.RollingFileAppender,log4net" >
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <!--Log/文件夹下面的 以时间命名的文件 -->
      <param name="File" type="" value="Log/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyyMMdd'.txt'" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} | [%t] | %-5p | %c | %m%n" />
      </layout>
    </appender>
    <!--记录到sqlserver数据库方式-->
    <!--<appender name="AdoNetAppender_SqlServer" 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="server=192.168.0.181;database=TopSystem;uid=TOPUSER;pwd=TOPSYS2010;"/>
            <commandText value="INSERT INTO SysLog ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)"/>
            <parameter>
                <parameterName value="@log_date"/>
                <dbType value="DateTime"/>
                <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}"/>
            </parameter>
            <parameter>
                <parameterName value="@thread"/>
                <dbType value="String"/>
                <size value="255"/>
                <layout type="log4net.Layout.PatternLayout" value="%thread"/>
            </parameter>
            <parameter>
                <parameterName value="@log_level"/>
                <dbType value="String"/>
                <size value="50"/>
                <layout type="log4net.Layout.PatternLayout" value="%level"/>
            </parameter>
            <parameter>
                <parameterName value="@logger"/>
                <dbType value="String"/>
                <size value="255"/>
                <layout type="log4net.Layout.PatternLayout" value="%logger"/>
            </parameter>
            <parameter>
                <parameterName value="@message"/>
                <dbType value="String"/>
                <size value="4000"/>
                <layout type="log4net.Layout.PatternLayout" value="%message"/>
            </parameter>
        </appender>-->
  </log4net>
</configuration>

在web.config配置:

<appSettings>
<!-- 作业调度配置 -->
<add key="cronExpr" value="00 18 16 ? * *"/>
</appSettings>

在global.asax配置如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Configuration;

namespace Webcode
{
    public class Global : System.Web.HttpApplication
    {
        Quartz.IScheduler sched;
        protected void Application_Start(object sender, EventArgs e)
        {
            ComLib.LogLib.Log4NetBase.Log("程序启动");
            //在应用程序启动时运行的代码
            Quartz.ISchedulerFactory sf = new Quartz.Impl.StdSchedulerFactory();
            sched = sf.GetScheduler();
            Quartz.JobDetail job = new Quartz.JobDetail("daily", "dailygroup", typeof(Webcode.BussniesLogic.Service.QuartzJobService));
            string cronExpr = ConfigurationManager.AppSettings["cronExpr"];
            Quartz.CronTrigger trigger = new Quartz.CronTrigger("daily_trigger", "dailygroup", "daily", "dailygroup", cronExpr);
            sched.AddJob(job, true);
            DateTime ft = sched.ScheduleJob(trigger);
            sched.Start();
            ComLib.LogLib.Log4NetBase.Log("程序启动结束");
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

本人不喜欢LOG文件记录太多没必要的信息,如果需要每次都记录可以在Application_Error里面添加:

View Code
 protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();

         if (ex != null)
        {
             ComLib.LogLib.Log4NetBase.Log(string.Format(@"错误的信息{0}--出错的方法名{1}--
               出错的类名{2}", ex.Message, ex.TargetSite.Name, ex.TargetSite.DeclaringType.FullName));
           }
            // 清空最后的错误
          Server.ClearError();
           Response.Redirect("/operate/error.htm");
}
View Code
public class QuartzJobService : IJob
    {
        #region IJob Members

        public void Execute(JobExecutionContext context)
        {
            ComLib.LogLib.Log4NetBase.Log("Job开始:" + DateTime.Now);
            DbSession.Default.FromProc("Report_Daily_Job").Execute();
            ComLib.LogLib.Log4NetBase.Log("JobReport_Daily_Job:" + DateTime.Now);
            DbSession.Default.FromProc("Report_Daily_TSL").Execute();
            ComLib.LogLib.Log4NetBase.Log("JobReport_Daily_TSL:" + DateTime.Now);
            DbSession.Default.FromProc("Report_Daily_ShortKey_TSL").Execute();
            ComLib.LogLib.Log4NetBase.Log("JobReport_Daily_ShortKey_TSL:" + DateTime.Now);
        }

        #endregion
    }

QuartzJobService.cs的代码如上

LOG4NETBASE.cs的代码如下

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ComLib.LogLib
{
   public class Log4NetBase
    {

       //TODO:现在还没考虑多log模块 所有关于LOG的都依赖LOG4NET
       /// <summary>
       /// 
       /// </summary>
       /// <param name="level">级别</param>
       /// <param name="UserName">所属用户 默认admin</param>
       /// <param name="StrAction">需要输出的信息</param>
       /// <param name="ex"></param>
        public static void Log(LogLevel level, string UserName, string StrAction, System.Exception ex)
        {


            LogEvent logevent = new LogEvent();
            logevent.Level = level;
            logevent.Message = StrAction;
            logevent.Ex = ex;
            logevent.Computer = System.Environment.MachineName;
            logevent.CreateTime = DateTime.Now;
            logevent.ThreadName = System.Threading.Thread.CurrentThread.Name;
            logevent.UserName = string.IsNullOrEmpty(UserName)?"admin":UserName;
            logevent.FinalMessage = LogFormatter.Format(null, logevent);

       

            switch (level)
            {
                case LogLevel.fatal:
                    LogBLL.fatal(logevent.FinalMessage);
                    break;
                case LogLevel.error:
                    LogBLL.error(logevent.FinalMessage);
                    break;
                case LogLevel.warn:
                    LogBLL.warn(logevent.FinalMessage);
                    break;
                case LogLevel.info:
                    LogBLL.info(logevent.FinalMessage);
                    break;
                case LogLevel.debug:
                    LogBLL.debug(logevent.FinalMessage);
                    break;
                default:
                    LogBLL.info(logevent.FinalMessage);
                    break;
            }

           

        }
        public static void Log(string StrAction, System.Exception ex) {
            Log(LogLevel.warn, "", StrAction, ex);
        }

        public static void Log(string StrAction)
        {
            Log(LogLevel.warn, "", StrAction, null);
        }
        public static void Log(System.Exception ex)
        {
            Log(LogLevel.warn, "", "系统错误", ex);
        }
        public static void LogWithDebugView(string StrAction, System.Exception ex) {
            if (ex != null)
            {
                Log(LogLevel.warn, "", StrAction, ex);
                Debug.DebugView.PrintDebug(StrAction, ex.Message);
            }
            else {
                Log(StrAction);
                Debug.DebugView.PrintDebug(StrAction);
            }
        }
        public static void LogWithDebugView(string StrAction)
        {
            LogWithDebugView(StrAction, null);
        }
    }

   /// <summary>
   /// Log formatter.
   /// </summary>
   public class LogFormatter
   {
       /// <summary>
       /// Quick formatter that toggles between delimited and xml.
       /// </summary>
       /// <param name="formatter"></param>
       /// <param name="logEvent"></param>
       public static string Format(string formatter, LogEvent logEvent)
       {
           if (string.IsNullOrEmpty(formatter))
               return Format(logEvent);

           if (formatter.ToLower().Trim() == "xml")
               return FormatXml(logEvent);

           return Format(logEvent);
       }


       /// <summary>
       /// Builds the log message using message and arguments.
       /// </summary>
       /// <param name="message">The message.</param>
       /// <param name="args">The args.</param>
       /// <returns></returns>
       public static string Format(LogEvent logEvent)
       {
           // Build a delimited string
           // <time>:<thread>:<level>:<message>
           StringBuilder line = new StringBuilder();
           if (!string.IsNullOrEmpty(logEvent.ThreadName))
               line.Append(logEvent.ThreadName+" | ");
           line.Append(logEvent.Level.ToString() + " | ");
           line.Append(logEvent.Message + " | ");
           line.Append(logEvent.Ex == null ? "无异常描述" : logEvent.Ex.Message);
           return line.ToString();
       }


       /// <summary>
       /// Builds the log message using message and arguments.
       /// </summary>
       /// <param name="message">The message.</param>
       /// <param name="args">The args.</param>
       /// <returns></returns>
       public static string FormatXml(LogEvent logEvent)
       {
           // Build a delimited string
           // <time>:<thread>:<level>:<loggername>:<message>
           string line = string.Format("<time>{0}</time>", logEvent.CreateTime.ToString());
           if (!string.IsNullOrEmpty(logEvent.ThreadName)) line += string.Format("<thread>{0}</thread>", logEvent.ThreadName);
           line += string.Format("<level>{0}</level>", logEvent.Level.ToString());
           line += string.Format("<message>{0}</message>", logEvent.Message);
           return line;
       }
   }
}

由于本人所用的框架限制不能黏贴太多代码,也是新手一枚,如果需要帮助请留言~欢迎大家批评共同进步

posted @ 2012-08-01 10:46  double_ed  Views(212)  Comments(0Edit  收藏  举报