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

摘要:
Directory.Exists(filePath)){Directory.CreateDirectory(filePath);}stringlogPath=AppDomain.CurrentDomain.BaseDirectory+"Log\"+DateTime.Now.ToString("yyyy-MM-dd")+".txt";try{using(StreamWritersw=File.AppendText(logPath)){sw.WriteLine("消息:"+msg);sw.WriteLine("时间:"+DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss"));sw.WriteLine("**************************************************");sw.WriteLine();sw.Flush();sw.Close();sw.Dispose();}}catch(IOExceptione){using(StreamWritersw=File.AppendText(logPath)){sw.WriteLine("异常:"+e.Message);sw.WriteLine("时间:"+DateTime.Now.ToString("yyy-MM-ddHH:mm:ss"));sw.WriteLine("**************************************************");sw.WriteLine();sw.Flush();sw.Close();sw.Dispose();}}}//////打印Model日志/////////publicstaticvoidWriteLog(Tmodel)whereT:class{stringfilePath=AppDomain.CurrentDomain.BaseDirectory+"Log";if(!

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

【C#写日志两个简单方法】第1张【C#写日志两个简单方法】第2张
public void WriteLog(stringmsg)  
{  
    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

利用泛型进行打印日志

【C#写日志两个简单方法】第1张【C#写日志两个简单方法】第4张
/// <summary>
///打印日志
/// </summary>
/// <param name="msg"></param>
public static void WriteLog(stringmsg)
{
    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

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

【C#写日志两个简单方法】第1张【C#写日志两个简单方法】第6张
public void WriteLog(string documentName, stringmsg)  
{  
    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") + "" +msg);  
    swLogFile.Close();  
    swLogFile.Dispose();  
}  
View Code

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

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

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

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

【C#写日志两个简单方法】第1张【C#写日志两个简单方法】第8张
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usinglog4net;
usinglog4net.Core;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespaceBoilerDashboard.Common
{
    public  classLogHelper
    {
        /// <summary>
        ///输出日志到Log4Net
        /// </summary>
        /// <param name="t"></param>
        /// <param name="ex"></param>
        #region static void WriteLog(Type t, Exception ex)
        public static voidWriteLog(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, stringmsg)
        {
            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效果如何

免责声明:文章转载自《【C#写日志两个简单方法】》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇GBT28181中的RTPB样条基函数的定义及系数的意义下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

C++ 解析Json——jsoncpp

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,和xml类似,本文主要对VS2008中使用Jsoncpp解析json的方法做一下记录。Jsoncpp是个跨平台的开源库,下载地址:http://sourceforge.net/projects/jsoncpp/。 方法一:使用Jsoncpp生成的lib文件 解压上...

linux定时重启节约内存

linux服务器上运行的一些程序,比较消耗内存,需要定时重启,进行内存定期释放 0 2 * * * sudo /sbin/reboot && echo $(date) '重启成功' >> ~/reboot_log.log 上面这种写法,日志是不会写入reboot_log.log的 crontab -u root -e 0 2 *...

熟悉Hbase常用命令及操作

(一) 编程实现以下指定功能,并用Hadoop提供的HBase Shell命令完成相同任务: 列出HBase所有的表的相关信息,例如表名; 在终端打印出指定的表的所有记录数据; 向已经创建好的表添加和删除指定的列族或列; 清空指定的表的所有记录数据; 统计表的行数。 (二)HBase数据库操作 1.现有以下关系型数据库中的表和数据,要求将其转换为适合于HB...

docker安装db2数据库

查询可安装的db2镜像 # docker search db2 [root@docker-servers ~]# docker search db2 INDEX NAME DESCRIPTION S...

artemis.http.client1.2 导致springboot日志不输出

今天遇到一个坑,就是以前maven本地仓库里面引入了海康的artmis.http.client jar包,这个包里面含有alibaba 的fastjson,我调用fastjson时,导入了这个依赖。虽然也能用。但是海康的这个包导致日志不输出,报错看不出来。 1.找到他的开发包,下载下来 地址:open.hikvision.com 2.配置maven,导入他...

php 面试题

1. 写一个函数,尽可能高效的,从一个标准 url 里取出文件的扩展名  例如: http://www.phpddt.com/abc/de/fg.php?id=1 需要取出 php 或 .php $url = 'http://www.baidu.com/wang/liu/4.php?i=90'; $urlArr = parse_url($url); $ex...