- using System;
- using System.IO;
- using Microsoft.VisualBasic.Logging;
- namespace MyLog
- {
- enum LogLevel
- {
- Error = 0,
- Warning,
- Notice,
- Info,
- Debug
- }
- static class FileLog
- {
- static FileLogTraceListener logtl = new FileLogTraceListener();
- static string fileName;
- public static LogLevel logLevel = LogLevel.Info;
- static FileLog()
- {
- logtl.Location = LogFileLocation.Custom;
- logtl.CustomLocation = AppDomain.CurrentDomain.BaseDirectory + @"..\\log";
- logtl.MaxFileSize = 5 * 1024 * 1024;
- logtl.DiskSpaceExhaustedBehavior = DiskSpaceExhaustedOption.ThrowException;
- logtl.AutoFlush = true;
- fileName = logtl.FullLogFileName;
- }
- public static void DebugLog(string format, params object[] args)
- {
- Log(LogLevel.Debug, format, args);
- }
- public static void ErrLog(string format, params object[] args)
- {
- Log(LogLevel.Error, format, args);
- }
- public static void Log(LogLevel level, string format, params object[] args)
- {
- if (level > logLevel)
- {
- return;
- }
- string prefix = string.Format("{0} [{1,-7}]", DateTime.Now.ToString(), level.ToString());
- string msg;
- if (args.Length > 0)
- {
- msg = string.Format(format, args);
- }
- else
- {
- msg = format;
- }
- string res = string.Format("{0} {1}", prefix, msg);
- try
- {
- logtl.WriteLine(res);
- }
- catch
- {
- try
- {
- File.Delete(fileName + ".old");
- File.Move(fileName, fileName + ".old");
- logtl.WriteLine(res);
- }
- catch { }
- }
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1501201614444.html
来源: http://www.codesnippet.cn/detail/1501201614444.html