欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#写日志类实例

程序员文章站 2024-02-11 17:58:16
本文实例讲述了c#写日志类,分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:using system; using system.configurat...

本文实例讲述了c#写日志类,分享给大家供大家参考。

具体实现方法如下:

复制代码 代码如下:
using system;
using system.configuration;
using system.io;
using system.threading;

namespace fqdservice.utils
{
    /// <summary>
    /// 写日志类
    /// </summary>
    public class filelogger
    {
        #region 字段
        public static readonly object _lock = new object();
        #endregion

        #region 写文件
        /// <summary>
        /// 写文件
        /// </summary>
        public static void writefile(string log, string path)
        {
            thread thread = new thread(new parameterizedthreadstart(delegate(object obj)
            {
                lock (_lock)
                {
                    if (!file.exists(path))
                    {
                        using (filestream fs = new filestream(path, filemode.create)) { }
                    }

                    using (filestream fs = new filestream(path, filemode.append, fileaccess.write))
                    {
                        using (streamwriter sw = new streamwriter(fs))
                        {
                            #region 日志内容
                            string value = string.format(@"{0}
--------------------------------------------------------
{1}

", datetime.now.tostring("yyyy-mm-dd hh:mm:ss"), obj.tostring());
                            #endregion

                            sw.writeline(value);
                            sw.flush();
                        }
                    }
                }
            }));
            thread.start(log);
        }
        #endregion

        #region 写日志
        /// <summary>
        /// 写日志
        /// </summary>
        public static void writelog(string log)
        {
            string logpath = configurationmanager.appsettings["logpath"] + "\\fqdservice_log.txt";
            writefile(log, logpath);
        }
        #endregion

        #region 写错误日志
        /// <summary>
        /// 写错误日志
        /// </summary>
        public static void writeerrorlog(string log)
        {
            string logpath = configurationmanager.appsettings["logpath"] + "\\fqdservice_errorlog.txt";
            writefile(log, logpath);
        }
        #endregion

    }
}

希望本文所述对大家的c#程序设计有所帮助。