C# 使用Log4Net記錄日誌(進階篇)

衣舞晨風發表於2015-11-02

配置檔案log4net_config.xml中的內容如下:

<?xml version="1.0" encoding="utf-8" ?>
<!-- 
		.NET application configuration file     
		This file must have the exact same name as your application with .config appended to it. 
		
		For example if your application is ConsoleApp.exe then the config file must be ConsoleApp.exe.config. 
		It must also be in the same directory as the application. 
	-->
<!-- This section contains the log4net configuration settings -->
<log4net>
	<!-- Define some output appenders -->
	<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
		<file value="rolling-log.txt" />
		<appendToFile value="true" />
		<maxSizeRollBackups value="10" />
		<maximumFileSize value="100" />
		<rollingStyle value="Size" />
		<staticLogFileName value="true" />
		<layout type="log4net.Layout.PatternLayout">
			<header value="[Header]
" />
			<footer value="[Footer]
" />
			<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
		</layout>
	</appender>
	<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
		<file value="log.txt" />
		<!-- Example using environment variables in params -->
		<!-- <file value="${TMP}\log-file.txt" /> -->
		<sppendToFile value="true" />
		<!-- An alternate output encoding can be specified -->
		<!-- <encoding value="unicodeFFFE" /> -->
		<layout type="log4net.Layout.PatternLayout">
			<header value="[Header]
" />
			<footer value="[Footer]
" />
			<conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline" />
		</layout>
		<!-- Alternate layout using XML			
			<layout type="log4net.Layout.XMLLayout" /> -->
	</appender>
	<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline" />
		</layout>
	</appender>
	<appender name="NetSendAppender" type="log4net.Appender.NetSendAppender">
		<threshold value="ERROR" />
		<server value="SQUARE" />
		<recipient value="nicko" />
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
		</layout>
	</appender>
	<!-- Example of how to configure the AdoNetAppender to connect to MS Access -->
	<appender name="ADONetAppender_Access" type="log4net.Appender.AdoNetAppender">
		<connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;" />
		<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
		<parameter>
			<parameterName value="@log_date" />
			<dbType value="String" />
			<size value="255" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date" />
			</layout>
		</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="1024" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%message" />
			</layout>
		</parameter>
	</appender>
	<!-- Example of how to configure the AdoNetAppender to connect to MS SQL Server -->
	<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="data source=192.168.110.110;initial catalog=DBtest;integrated security=false;persist security info=True;User ID=sa;Password=saPassword" />
		<commandText value="INSERT INTO Log ([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">
					<conversionPattern value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
				</layout> 
				-->
			<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>
	</appender>
	<!-- Setup the root category, add the appenders and set the default level -->
	<root>
		<level value="DEBUG" />
		<appender-ref ref="LogFileAppender" />
		<appender-ref ref="ADONetAppender_SqlServer" />
		<!--<appender-ref ref="ConsoleAppender" />-->
	</root>
</log4net>
該配置檔案可以用於往文字檔案及sql server資料庫中記錄日誌(啟用哪一個由下面的配置決定):

<appender-ref ref="LogFileAppender" />
<appender-ref ref="ADONetAppender_SqlServer" />

日誌類封裝:

/// <summary>
    /// 日誌記錄類(記錄到資料庫)
    /// </summary>
    public static class LogisTracToSqlDB
    {
        private static readonly log4net.ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private const string LOG4NET_CONFIG = "log4net_config.xml";

        static LogisTracToSqlDB()
        {
            try
            {
                ConfigureLoad();
            }
            catch { }
        }

        /// <summary>
        /// 輸出日誌
        /// </summary>
        /// <param name="sInfo"></param>
        public static void WriteLog(string sInfo)
        {
            m_log.Error(sInfo);
        }
        /// <summary>
        /// 記錄debug資訊
        /// </summary>
        /// <param name="e"></param>
        public static void WriteLog(Exception e)
        {
            WriteLog(e.ToString());
            //WriteLog("--------------------------------------[本次異常開始]--------------------------------------");
            //WriteLog("Message : " + e.Message);
            //WriteLog("Source : " + e.Source);
            //WriteLog("StackTrace : " + e.StackTrace);
            //WriteLog("TargetSite : " + e.TargetSite);
            //WriteLog("--------------------------------------[本次異常結束]--------------------------------------\r\n");
        }

        /// <summary>
        /// 配置log4net環境
        /// </summary>
        private static void ConfigureLoad()
        {
            XmlDocument doc = new XmlDocument();
            //使用當前dll路徑
            string sPath = FilesOperate.GetAssemblyPath();
            if (!sPath.EndsWith("\\"))
            {
                sPath += "\\";
            }                  
            sPath += LOG4NET_CONFIG;
            doc.Load(@sPath);
            XmlElement myElement = doc.DocumentElement;
            log4net.Config.XmlConfigurator.Configure(myElement);
        }
    }
    /// <summary>
    /// 日誌記錄類(記錄到文字檔案中)
    /// </summary>
    public static class LogisTrac
    {
        private static readonly string LOG_DIR = "日誌";
        private static readonly string LOG_FILE = LOG_DIR + "\\log" + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
        private const string LOG4NET_CONFIG = "log4net_config.xml";
        private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(typeof(LogisTrac));


        static LogisTrac()
        {
            try
            {
                ConfigureLoad();
            }
            catch { }
        }

        /// <summary>
        /// 返回ILog介面
        /// </summary>
        private static log4net.ILog Log
        {
            get
            {
                return m_log;
            }
        }

        /// <summary>
        /// 輸出日誌
        /// </summary>
        /// <param name="sInfo"></param>
        public static void WriteLog(string sInfo)
        {
            m_log.Error(sInfo);
        }


        /// <summary>
        /// 記錄debug資訊
        /// </summary>
        /// <param name="e"></param>
        public static void WriteLog(Exception e)
        {
            WriteLog("--------------------------------------[本次異常開始]--------------------------------------");
            WriteLog("Message : " + e.Message);
            WriteLog("Source : " + e.Source);
            WriteLog("StackTrace : " + e.StackTrace);
            WriteLog("TargetSite : " + e.TargetSite);
            WriteLog("--------------------------------------[本次異常結束]--------------------------------------\r\n");
        }

        /// <summary>
        /// 配置log4net環境
        /// </summary>
        private static void ConfigureLoad()
        {
            XmlDocument doc = new XmlDocument();
            //使用當前dll路徑
            string sPath = FilesOperate.GetAssemblyPath();

            if (!sPath.EndsWith("\\"))
            {
                sPath += "\\";
            }

            //檢視Log資料夾是否存在,如果不存在,則建立
            string sLogDir = sPath + LOG_DIR;
            if (!Directory.Exists(sLogDir))
            {
                Directory.CreateDirectory(sLogDir);
            }
            string sLogFile = sPath + LOG_FILE;
            sPath += LOG4NET_CONFIG;
            doc.Load(@sPath);
            XmlElement myElement = doc.DocumentElement;

            //修改log.txt的路徑
            XmlNode pLogFileAppenderNode = myElement.SelectSingleNode("descendant::appender[@name='LogFileAppender']/file");
            // Create an attribute collection from the element.
            XmlAttributeCollection attrColl = pLogFileAppenderNode.Attributes;
            attrColl[0].Value = sLogFile;

            log4net.Config.XmlConfigurator.Configure(myElement);
        }

    }

    /// <summary>
    /// 檔案 操作
    /// </summary>
    public static class FilesOperate
    {
        /// <summary>
        /// 獲取App的當前路徑 \\結束
        /// </summary>
        /// <returns></returns>
        public static string getAppPath()
        {
            return GetAssemblyPath();
        }

        /// <summary>
        /// 獲取Assembly的執行路徑 \\結束
        /// </summary>
        /// <returns></returns>
        public static string GetAssemblyPath()
        {
            string sCodeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

            sCodeBase = sCodeBase.Substring(8, sCodeBase.Length - 8);    // 8是 file:// 的長度

            string[] arrSection = sCodeBase.Split(new char[] { '/' });

            string sDirPath = "";
            for (int i = 0; i < arrSection.Length - 1; i++)
            {
                sDirPath += arrSection[i] + Path.DirectorySeparatorChar;
            }

            return sDirPath;
        }

        /// <summary>
        /// 資料夾複製
        /// </summary>
        /// <param name="sSourceDirName">原始路徑</param>
        /// <param name="sDestDirName">目標路徑</param>
        /// <returns></returns>
        public static bool CopyDirectory(string sSourceDirName, string sDestDirName)
        {
            if (string.IsNullOrEmpty(sSourceDirName) || string.IsNullOrEmpty(sDestDirName))
            {
                return false;
            }

            //不復制.svn資料夾
            if (sSourceDirName.EndsWith("svn"))
            {
                return true;
            }

            if (sSourceDirName.Substring(sSourceDirName.Length - 1) != Path.DirectorySeparatorChar.ToString())
            {
                sSourceDirName = sSourceDirName + Path.DirectorySeparatorChar;
            }
            if (sDestDirName.Substring(sDestDirName.Length - 1) != Path.DirectorySeparatorChar.ToString())
            {
                sDestDirName = sDestDirName + Path.DirectorySeparatorChar;
            }

            #region 複製函式
            if (Directory.Exists(sSourceDirName))
            {
                if (!Directory.Exists(sDestDirName))
                {
                    Directory.CreateDirectory(sDestDirName);
                }
                foreach (string item in Directory.GetFiles(sSourceDirName))
                {
                    File.Copy(item, sDestDirName + System.IO.Path.GetFileName(item), true);
                }
                foreach (string item in Directory.GetDirectories(sSourceDirName))
                {
                    CopyDirectory(item, sDestDirName + item.Substring(item.LastIndexOf(Path.DirectorySeparatorChar) + 1));
                }
            }
            return true;
            #endregion
        }


        /// <summary> 
        /// 啟動其他的應用程式 
        /// </summary> 
        /// <param name="file">應用程式名稱</param> 
        /// <param name="workdirectory">應用程式工作目錄</param> 
        /// <param name="args">命令列引數</param> 
        /// <param name="style">視窗風格</param> 
        public static bool StartProcess(string file, string workdirectory, string args, ProcessWindowStyle style)
        {
            try
            {
                Process pMyProcess = new Process();
                ProcessStartInfo pStartInfo = new ProcessStartInfo(file, args);
                pStartInfo.WindowStyle = style;
                pStartInfo.WorkingDirectory = workdirectory;
                pMyProcess.StartInfo = pStartInfo;
                pMyProcess.StartInfo.UseShellExecute = false;
                pMyProcess.Start();
                return true;
            }
            catch (Exception ex)
            {
                //LogAPI.debug(ex);
                return false;
            }
        }

        /// <summary>
        /// 獲得本地計算機名
        /// </summary>
        /// <returns></returns>
        public static string GetComputerName()
        {
            return Dns.GetHostName();
        }

        /// <summary>
        /// 獲得計算機IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIPAddress()
        {
            try
            {
                string sComputerName;
                sComputerName = GetComputerName();
                string sIpAddress = "";
                IPAddress[] addr = Dns.GetHostAddresses(sComputerName);
                //for (int i = 0; i < addr.Length; i++)
                //{
                //    sIpAddress += addr[i].ToString() + " ";
                //}
                sIpAddress = addr[0].ToString();
                return sIpAddress;
            }
            catch (Exception ep)
            {
                //LogAPI.debug(ep);
                return "127.0.0.1";
            }
        }

        /// <summary>
        /// 描述:建立目錄
        /// </summary>
        /// <returns></returns>
        public static bool CreateFolder(string sFolder)
        {
            //如果臨時資料夾不存在,則建立該資料夾
            if (!Directory.Exists(sFolder))
            {
                Directory.CreateDirectory(sFolder);
            }
            return true;
        }
    }


log4net 基礎篇:點選開啟連結
原始碼下載地址:點選開啟連結 




相關文章