欢迎来到【一个大西瓜】的博客

不曾为梦想奋斗,拿什么去燃烧青春。有梦之人亦终将老去,但少年心气如昨。
太阳每一个时刻都同时是夕阳和朝阳,每天她沉入西边,意味着她同时从另一面土地升起。
扩大
缩小

【C#写日志两个简单方法】

方法一:以日期为日志文件名.

public void WriteLog(string msg)  
{  
    string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";  
    if (!Directory.Exists(filePath))  
    {  
        Directory.CreateDirectory(filePath);  
    }  
    string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";  
    try  
    {  
        using (StreamWriter sw = File.AppendText(logPath))  
        {  
            sw.WriteLine("消息:" + msg);  
            sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));  
            sw.WriteLine("**************************************************");  
            sw.WriteLine();  
            sw.Flush();  
            sw.Close();  
            sw.Dispose();  
        }  
    }  
    catch (IOException e)  
    {  
        using (StreamWriter sw = File.AppendText(logPath))  
        {  
            sw.WriteLine("异常:" + e.Message);  
            sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));  
            sw.WriteLine("**************************************************");  
            sw.WriteLine();  
            sw.Flush();  
            sw.Close();  
            sw.Dispose();  
        }  
    }  
}  
View Code

利用泛型进行打印日志

/// <summary>
/// 打印日志
/// </summary>
/// <param name="msg"></param>
public static void WriteLog(string msg)
{
    string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
    if (!Directory.Exists(filePath))
    {
        Directory.CreateDirectory(filePath);
    }
    string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
    try
    {
        using (StreamWriter sw=File.AppendText(logPath))
        {
            sw.WriteLine("消息:" + msg);
            sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sw.WriteLine("**************************************************");
            sw.WriteLine();
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }
    catch (IOException e)
    {
        using (StreamWriter sw = File.AppendText(logPath))
        {
            sw.WriteLine("异常:" + e.Message);
            sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
            sw.WriteLine("**************************************************");
            sw.WriteLine();
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }
}

/// <summary>
/// 打印Model日志
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
public static void WriteLog<T>(T model) where T:class
{
    string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
    if (!Directory.Exists(filePath))
    {
        Directory.CreateDirectory(filePath);
    }
    string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
    try
    {
        using (StreamWriter sw = File.AppendText(logPath))
        {
            Type type = typeof(T);
            string msg = string.Join("*****", type.GetProperties().Select(m=>m.Name+":"+m.GetValue(model)));
            
            sw.WriteLine("消息:" + msg);
            sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sw.WriteLine("**************************************************");
            sw.WriteLine();
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }
    catch (IOException e)
    {
        using (StreamWriter sw = File.AppendText(logPath))
        {
            sw.WriteLine("异常:" + e.Message);
            sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
            sw.WriteLine("**************************************************");
            sw.WriteLine();
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }
}
View Code

 

方法二:以文档名称和日期结合作为文件名

public void WriteLog(string documentName, string msg)  
{  
    string errorLogFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");  
    if (!System.IO.Directory.Exists(errorLogFilePath))  
    {  
        System.IO.Directory.CreateDirectory(errorLogFilePath);  
    }  
    string logFile = System.IO.Path.Combine(errorLogFilePath, documentName + "@" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt");  
    bool writeBaseInfo = System.IO.File.Exists(logFile);  
    StreamWriter swLogFile = new StreamWriter(logFile, true, Encoding.Unicode);  
    swLogFile.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t" + msg);  
    swLogFile.Close();  
    swLogFile.Dispose();  
}  
View Code

 

方法三: 使用log4net类库输出日志

  1.下载log4net类库 并选择项目对应的框架版本

   下载地址:http://logging.apache.org/log4net/download_log4net.cgi

  2.添加log4net引用,创建LogHelper类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Core;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace BoilerDashboard.Common
{
    public  class LogHelper
    {
        /// <summary>
        /// 输出日志到Log4Net
        /// </summary>
        /// <param name="t"></param>
        /// <param name="ex"></param>
        #region static void WriteLog(Type t, Exception ex)

        public static void WriteLog(Type t, Exception ex)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(t);
            log.Error("Error", ex);
        }

        #endregion

        /// <summary>
        /// 输出日志到Log4Net
        /// </summary>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        #region static void WriteLog(Type t, string msg)

        public static void WriteLog(Type t, string msg)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(t);
            log.Error(msg);
        }

        #endregion


        
    }
}
View Code

 

方法四:Microsoft Enterprise Library里面的Log功能  

    以VS2012里面建立的一个控制台程序为例

  1. 安装Microsoft Enterprise Library里面的Logging Application模块。
  在需要使用Log功能的项目上面右键,选择Manage NuGet Packeages...
  2. 在Manage NuGet Packeages窗口里面找到Enterprise Library - Logging Application Block,然后安装
  安装成功以后,项目引用中会增加两个新的引用。

  3. 我们需要对App.config文件进行配置。在这里我们使用配置编辑工具:Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix。这个工具的下载地址:http://www.microsoft.com/en-us/download/details.aspx?id=38789

  4. 配置App.config文件。右键App.config文件选择Edit configuration file v6,打开配置工具窗口。
  5. 选择菜单命令Block -> Add Logging Settings
  6. 在Logging Target Listeners里面点加号按钮,然后选择Add Rolling Flat File Trace Listener(生成可以进行自动分割的文本文件)。
  7. 一般需要设置的参数有:Asynchronous(选true则进行异步log), File Exist Behavior(选), File Name, Formatter Name, Max Archived Files, Roll Interval, Roll Size KB。
  其中Formatter Name的值从Log Message Formatters中生成的值中选取。

  8. 生成 Message Format。在Log Message Formatters中点击加号按钮,选择Add Text Formatter
  点击Template右侧的...按钮,打开Template Editor对话框,对Template的内容进行编辑
  编辑后在App.config中生成的xml代码如下:
  Logging formatter
  9. 在窗口左侧区域中点击Cotegories右边的加号按钮。生成一个新的Category
  10. 在新生成的Category区域中修改Name属性,然后点击Listeners右边的加号按钮,选择在Logging Target Listeners区域中已经生成的Listener。
  11. 对已经进行的设置保
  12. 写个简单的测试程序看看生成的Log效果如何

 

posted on 2017-12-11 15:43  一个大西瓜咚咚咚  阅读(12752)  评论(0编辑  收藏  举报

导航