C# 创建系统日志、文件日志

使用C#自带的EventLog方法来操作系统日志。
        /// 
        /// 日志文件记录 
        /// 
        /// 程序
        /// 内容
        public static void Log(string program, string msg)
        {
            string path = Path.Combine("./log");
            if (!Directory.Exists(path))//判断是否有该文件  
                Directory.CreateDirectory(path);//不存在则创建log文件夹
            string info = path + "\\" + program;
            if (!Directory.Exists(info))
                Directory.CreateDirectory(info);
            string logFileName = path + "\\" + program + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//生成日志文件
            StreamWriter writer;
            try
            {
                writer = File.AppendText(logFileName);//文件中添加文件流
                writer.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " " + msg);
                writer.Flush();
                writer.Close();
            }
            catch (Exception e)
            {
                writer = File.AppendText(logFileName);
                writer.WriteLine(DateTime.Now.ToString("日志记录错误HH:mm:ss") + " " + e.Message + " " + msg);
                writer.Flush();
                writer.Close();
            }
        }
        /// 
        /// 系统日志记录
        /// 
        /// 
        /// 
        public static void system(string info,string msg)
        {
            //删除事件日志
            //EventLog.Delete("MyLog");
            //删除事件源
            //EventLog.DeleteEventSource(info);


            //判断info事件源是否存在系统上
            if (!EventLog.SourceExists(info))
                //创建事件源
               EventLog.CreateEventSource(info, "MyLog");
            //(注册事件源,信息,事件级别,事件ID,任务类型)
            EventLog.WriteEntry(info, msg, EventLogEntryType.Error,2264,1);
        }

你可能感兴趣的:(c#,系统日志)