EventLog 把日志写入注册表或文本的方法

本文介绍了一个用于写入和读取事件日志的实用类。该类提供了多种方法来记录不同类型的事件(如错误、警告和信息),并能将这些事件写入文件或系统注册表中。同时,也提供了清除事件日志和从注册表中读取事件日志的功能。

using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Data;

namespace EventsLog
{
    public class LogWriter
    {
        /// <summary>
        /// Write EventLog into ~/Log/Error.Log.
        /// </summary>
        /// <param name="message">Message</param>
        public static void WriteToFile(string message)
        {
            WriteToFile(message, "Error.Log");
        }

        /// <summary>
        /// Write EventLog to file of given path.
        /// </summary>
        /// <param name="message">Message</param>
        /// <param name="path">Path of file</param>
        public static void WriteToFile(string message, string path)
        {
            try
            {
                StreamWriter sw = new StreamWriter(path, true, Encoding.Unicode);
                sw.WriteLine("============================================================================");
                sw.WriteLine("Time Generated:");
                sw.WriteLine("   " + System.DateTime.Now.ToString());
                sw.WriteLine("/r/nMessage:");
                sw.WriteLine(message);
                sw.WriteLine("/r/n/r/n/r/n");
                //Must close the stream.
                sw.Close();
            }
            catch { }
        }

        /// <summary>
        /// Write EventLog of Error type to register.
        /// </summary>
        /// <param name="message">Message</param>
        public static void WriteErrorToReg(string message)
        {
            WriteToReg(message, EventLogEntryType.Error);
        }

        /// <summary>
        /// Write EventLog of Information type to register.
        /// </summary>
        /// <param name="message">Message</param>
        public static void WriteInfoToReg(string message)
        {
            WriteToReg(message, EventLogEntryType.Information);
        }

        /// <summary>
        /// Write EventLog of Warning type to register.
        /// </summary>
        /// <param name="message">Message</param>
        public static void WriteWarningToReg(string message)
        {
            WriteToReg(message, EventLogEntryType.Warning);
        }

        /// <summary>
        /// Write EventLog to register.
        /// </summary>
        /// <param name="message">Message</param>
        /// <param name="type">Type
        /// {
        ///  Error = EventLogEntryType.Error,
        ///  Information = EventLogEntryType.Information,
        ///  Warning = EventLogEntryType.Warning.
        /// }</param>
        public static void WriteToReg(string message, EventLogEntryType type)
        {
            try
            {
                //Get EventLog.
                EventLog eventLog = getEventLog();

                //Write message to EventLog.
                eventLog.WriteEntry(message, type);
            }
            catch (Exception e)
            {
                WriteToFile(e.ToString());
            }
        }

        /// <summary>
        /// Read EventLog from register.
        /// </summary>
        /// <returns>Return DataTable with all EventLog info.</returns>
        public static DataTable ReadFromReg()
        {
            //Get EventLog.
            EventLog eventLog = getEventLog();

            //Construct a DataTable Object,with 3 columns : EntryType、TimeGenerated、Message
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("EntryType", System.Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("TimeGenerated", System.Type.GetType("System.DateTime")));
            dt.Columns.Add(new DataColumn("Message", System.Type.GetType("System.String")));

            //Read EventLog,and add all to DataTable
            foreach (EventLogEntry entry in eventLog.Entries)
            {
                dt.Rows.Add(new object[] { entry.EntryType, entry.TimeGenerated, entry.Message });
            }

            return dt;
        }

        /// <summary>
        /// Clear EventLog from register.
        /// </summary>
        /// <returns>Return is whether successful.</returns>
        public static bool ClearFromReg()
        {
            try
            {
                //Get EventLog.
                EventLog eventLog = getEventLog();

                //Clear all EventLog.
                eventLog.Clear();

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Get EventLog which source is "WebApplication".
        /// </summary>
        /// <returns>EventLog with special source.</returns>
        private static EventLog getEventLog()
        {
            string source = "WebApplication";

            //Make sure EventLog of special source exist.
            if (!(EventLog.SourceExists(source)))
            {
                EventLog.CreateEventSource(source, "Application");
            }

            //New an EventLog Object, and set the source.
            EventLog eventLog = new EventLog("Application");
            eventLog.Source = source;

            return eventLog;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值