using System; using System.Collections.Generic; using System.Linq; using System.Text; using Aitex.Core.Util; using log4net.Core; using System.Diagnostics; using System.IO; namespace Aitex.Core.RT.Log { public class LogManager : ICommonLog { public const int MaxLogsMonth = 3; PeriodicJob _loggingJob; PeriodicJob _threadDeleteLogs; FixSizeQueue _logQueue; LogWriter _writer; public LogManager() { } public void Initialize() { _logQueue = new FixSizeQueue(1000); _loggingJob = new PeriodicJob(300, this.PeriodicRun, "Save Log Job", true); _threadDeleteLogs = new PeriodicJob(1000 * 60 * 60 * 24, OnDeleteLog, "Delete Log Thread", true); _writer = new LogWriter(); LOG.InnerLogger = this; } public void Terminate() { try { if (_loggingJob != null) { _loggingJob.Stop(); _loggingJob = null; } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } public void Info(string message, bool isTraceOn, string stackFile) { CacheLog(message, Level.Info, null, isTraceOn, stackFile); } public void Warning(string message) { CacheLog(message, Level.Warn, null, true, null); } public void Warning(string message, string stackFile) { CacheLog(message, Level.Warn, null, true, stackFile); } public void Error(string message, string stackFile) { CacheLog(message, Level.Error, null, true, stackFile); } public void Warning(string message, Exception ex, string stackFile) { CacheLog(message, Level.Warn, ex, true, stackFile); } public void Error(string message, Exception ex, string stackFile) { CacheLog(message, Level.Error, ex, true, stackFile); } bool PeriodicRun() { LogItem item; while (_logQueue.TryDequeue(out item)) { string log = _writer.Write(item); } return true; } bool OnDeleteLog() { try { string path = string.Format(@"{0}", "Logs"); FileInfo[] fileInfos; DirectoryInfo curFolderInfo = new DirectoryInfo(path); fileInfos = curFolderInfo.GetFiles(); foreach (FileInfo info in fileInfos) { if (info.Name.Contains("log") && info.Extension == ".txt") { DateTime lastWriteTime = DateTime.Parse(info.LastWriteTime.ToShortDateString()); DateTime intervalTime = DateTime.Now.AddMonths(-MaxLogsMonth);// DateTime.Parse(DateTime.Now.AddMonths(-1).ToShortDateString()); if (lastWriteTime < intervalTime) { File.Delete(info.FullName); //LOG.Write(string.Format("【log】自动删除log成功,logName:{0}", info.Name)); } } } } catch (Exception ex) { LOG.Write(ex); } return true; } void CacheLog(string message, Level level, Exception exception, bool isTraceOn, string stackFile) { //if (isTraceOn) //{ // System.Diagnostics.Trace.WriteLine(message + (exception == null ? "" : exception.Message)); //} _logQueue.Enqueue(new LogItem(message, new StackTrace(true).GetFrame(5), level, exception, stackFile)); } } }