您的位置:首页 > 编程语言 > C#

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

2017-12-11 15:43 417 查看

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

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效果如何
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: