.net生成日志处理,记录产生,异常的模块,进程号,线程号:
2008-05-08 16:52
513 查看
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Threading;
using System.Windows.Forms;
namespace Tigerleq.Log
...{
public class LogOperate
...{
// Fields
private const string APPERREXCEPTIONTYPENAME = "Common.Exception.AppErrException";
private FileStream m_fileStreamLog;
private int m_iSleepTime;
private int m_iTempTryCnt;
private int m_iTryCnt;
private string m_sFile;
private string m_sMainPath;
private string m_sPath;
private string m_sTime;
private string m_sXmlLog;
// Methods
public LogOperate()
...{
this.m_sMainPath = Application.StartupPath + @"logApp";
this.m_iSleepTime = 200;
this.m_iTryCnt = 10;
this.m_iTempTryCnt = 10;
this.m_sPath = "";
this.m_sFile = "";
this.m_sTime = "";
this.m_fileStreamLog = null;
this.m_sXmlLog = null;
}
public LogOperate(string p_sDirectory)
...{
this.m_sMainPath = Application.StartupPath + @"logApp";
this.m_iSleepTime = 200;
this.m_iTryCnt = 10;
this.m_iTempTryCnt = 10;
this.m_sPath = "";
this.m_sFile = "";
this.m_sTime = "";
this.m_fileStreamLog = null;
this.m_sXmlLog = null;
if ((p_sDirectory != null) && !(p_sDirectory == ""))
...{
this.m_sMainPath = Application.StartupPath + @"log" + p_sDirectory.Trim() + @"";
}
}
public void Init(XmlNode p_nd)
...{
try
...{
this.m_sMainPath = @"." + p_nd.SelectSingleNode("MainPath").Value.Trim() + @"";
this.m_iSleepTime = int.Parse(p_nd.SelectSingleNode("SleepTime").Value);
this.m_iTryCnt = int.Parse(p_nd.SelectSingleNode("TryCnt").Value);
this.m_iTempTryCnt = int.Parse(p_nd.SelectSingleNode("TempTryCnt").Value);
}
catch
...{
}
}
private FileStream OpenLog(string p_sPathFile)
...{
FileStream stream2;
try
...{
bool flag;
int num = 0;
goto Label_003F;
Label_0006: ;
try
...{
return new FileStream(p_sPathFile, FileMode.Append, FileAccess.Write, FileShare.Read);
}
catch (IOException)
...{
num++;
if (num >= this.m_iTryCnt)
...{
return null;
}
Thread.Sleep(this.m_iSleepTime);
}
Label_003F:
flag = true;
goto Label_0006;
}
catch (Exception)
...{
stream2 = null;
}
return stream2;
}
private FileStream OpenTempLog(string p_sPath, string p_sTime)
...{
FileStream stream2;
try
...{
bool flag;
int num = 0;
DateTime time = DateTime.Parse(p_sTime);
string str = time.Year.ToString() + time.Month.ToString("0#") + time.Day.ToString("0#") + time.Hour.ToString("0#") + time.Minute.ToString("0#") + time.Second.ToString("0#");
goto Label_017A;
Label_00B1: ;
try
...{
return new FileStream(p_sPath + str + "-" + num.ToString() + ".log", FileMode.Append, FileAccess.Write, FileShare.Read);
}
catch (IOException exception)
...{
num++;
if (num >= this.m_iTempTryCnt)
...{
MessageBox.Show((("多次尝试打开临时日志文件,依然失败 " + exception.Message) + " " + exception.ToString()) + " " + exception.StackTrace);
return null;
}
}
Label_017A:
flag = true;
goto Label_00B1;
}
catch (Exception)
...{
stream2 = null;
}
return stream2;
}
public void OperateExp(Exception p_ex)
...{
LogErr logErr = new LogErr(p_ex, "未知错误");
Write(logErr);
logErr.Dispose();
}
public void OperateExp(Exception p_ex, string p_sAddMsg, string p_sShowMsg)
...{
LogErr logErr = new LogErr(p_ex, "p_sAddMsg");
Write(logErr);
logErr.Dispose();
}
public void Write(LogBase p_log)
...{
try
...{
string str = "";
MemoryStream stream = new MemoryStream();
StreamReader reader = new StreamReader(stream, Encoding.Default);
string str2 = null;
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
this.m_sPath = this.m_sMainPath + DateTime.Parse(p_log.Time).Year.ToString() + DateTime.Parse(p_log.Time).Month.ToString("0#") + @"";
Directory.CreateDirectory(this.m_sPath);
this.m_sFile = DateTime.Parse(p_log.Time).Year.ToString() + DateTime.Parse(p_log.Time).Month.ToString("0#") + DateTime.Parse(p_log.Time).Day.ToString("0#") + ".log";
str = this.m_sPath + this.m_sFile;
writer.Formatting = Formatting.Indented;
string fullName = p_log.GetType().FullName;
string localName = fullName.Substring(fullName.LastIndexOf(".") + 1).Trim();
writer.WriteStartElement(localName);
writer.WriteElementString("Time", p_log.Time);
writer.WriteElementString("ProcessID", p_log.ProcessID.ToString());
writer.WriteElementString("ThreadID", p_log.ThreadID.ToString());
writer.WriteElementString("AddMsg", p_log.AddMsg);
switch (localName)
...{
case "LogInfo":
writer.WriteElementString("Info", ((LogInfo)p_log).Info);
break;
case "LogWarn":
writer.WriteElementString("Warn", ((LogWarn)p_log).Warn);
writer.WriteElementString("StackTrace", ((LogWarn)p_log).stackTrace.ToString());
break;
case "LogErr":
writer.WriteElementString("Message", ((LogErr)p_log).Message);
writer.WriteElementString("ExceptionStackTrace", ((LogErr)p_log).ExceptionStackTrace);
writer.WriteElementString("ExceptionStr", ((LogErr)p_log).ExceptionStr);
writer.WriteElementString("Source", ((LogErr)p_log).Source);
writer.WriteElementString("StackTrace", ((LogErr)p_log).StackTrace);
break;
}
writer.WriteEndElement();
writer.Flush();
reader.BaseStream.Seek(0L, SeekOrigin.Begin);
str2 = reader.ReadToEnd();
str2 = " " + str2 + " ";
writer.Close();
reader.Close();
stream.Close();
this.m_sTime = p_log.Time;
this.m_sXmlLog = str2;
new Thread(new ThreadStart(this.WriteToFile)).Start();
}
catch (Exception exception)
...{
throw exception;
}
}
public void WriteExp(Exception p_ex)
...{
LogErr err = new LogErr(p_ex, "");
this.Write(err);
}
private void WriteToFile()
...{
string str = this.m_sPath + this.m_sFile;
this.m_fileStreamLog = this.OpenLog(str);
if (this.m_fileStreamLog == null)
...{
this.m_fileStreamLog = this.OpenTempLog(this.m_sPath, this.m_sTime);
}
if (this.m_fileStreamLog != null)
...{
StreamWriter writer = new StreamWriter(this.m_fileStreamLog, Encoding.Default);
writer.Write(this.m_sXmlLog);
writer.Close();
this.m_fileStreamLog.Close();
}
}
}
}
基类
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
namespace Tigerleq.Log
...{
public abstract class LogBase : IDisposable
...{
// Pointer to an external unmanaged resource.
private IntPtr handle;
// Other managed resource this class uses.
private Component Components;
// Track whether Dispose has been called.
private bool disposed = false;
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
...{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected virtual void Dispose(bool disposing)
...{
// Check to see if Dispose has already been called.
if (!this.disposed)
...{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
...{
// Dispose managed resources.
Components.Dispose();
}
// Release unmanaged resources. If disposing is false,
// only the following code is executed.
CloseHandle(handle);
handle = IntPtr.Zero;
// Note that this is not thread safe.
// Another thread could start disposing the object
// after the managed resources are disposed,
// but before the disposed flag is set to true.
// If thread safety is necessary, it must be
// implemented by the client.
}
disposed = true;
}
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~LogBase()
...{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
// Fields
/**//// <summary>
///
/// </summary>
/// <param name="hObject"> handle to object</param>
/// <returns></returns>
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
protected string m_AddMsg;
protected int m_iProcessID;
protected int m_iThreadID;
protected string m_sTime;
// Methods
public LogBase()
...{
this.m_iProcessID = -1;
this.m_iThreadID = -1;
this.m_sTime = null;
this.m_AddMsg = null;
}
public LogBase(string p_sAddMsg)
...{
this.m_iProcessID = -1;
this.m_iThreadID = -1;
this.m_sTime = null;
this.m_AddMsg = null;
this.m_AddMsg = p_sAddMsg.Trim();
this.m_sTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
this.m_iProcessID = Process.GetCurrentProcess().Id;
this.m_iThreadID = AppDomain.GetCurrentThreadId();
}
// Properties
public string AddMsg
...{
get
...{
return this.m_AddMsg;
}
}
public int ProcessID
...{
get
...{
return this.m_iProcessID;
}
}
public int ThreadID
...{
get
...{
return this.m_iThreadID;
}
}
public string Time
...{
get
...{
return this.m_sTime;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Security;
using System.Windows.Forms;
namespace Tigerleq.Log
...{
public class LogErr : LogBase
...{
// Fields
private string m_sExceptionStackTrace;
private string m_sExceptionStr;
private string m_sMessage;
private string m_sOtherMessage;
private string m_sSource;
private string m_sStackTrace;
// Methods
public LogErr()
...{
this.m_sMessage = null;
this.m_sOtherMessage = "";
this.m_sExceptionStackTrace = null;
this.m_sExceptionStr = null;
this.m_sSource = null;
this.m_sStackTrace = null;
}
public LogErr(Exception p_ex, string p_sAddMsg)
: base(p_sAddMsg)
...{
this.m_sMessage = null;
this.m_sOtherMessage = "";
this.m_sExceptionStackTrace = null;
this.m_sExceptionStr = null;
this.m_sSource = null;
this.m_sStackTrace = null;
this.m_sMessage = p_ex.Message;
this.m_sExceptionStackTrace = p_ex.StackTrace;
this.m_sExceptionStr = p_ex.ToString();
this.m_sSource = p_ex.Source;
this.m_sStackTrace = new StackTrace().ToString();
if (p_ex is ArgumentException)
...{
this.m_sOtherMessage = this.m_sOtherMessage + "相关参数:" + ((ArgumentException)p_ex).ParamName;
}
if (p_ex is SecurityException)
...{
this.m_sOtherMessage = this.m_sOtherMessage + "权限状态:" + ((SecurityException)p_ex).PermissionState;
}
}
// Properties
public string ExceptionStackTrace
...{
get
...{
return this.m_sExceptionStackTrace;
}
}
public string ExceptionStr
...{
get
...{
return this.m_sExceptionStr;
}
}
public string Message
...{
get
...{
return this.m_sMessage;
}
}
public string OtherMessage
...{
get
...{
return this.m_sOtherMessage;
}
}
public string Source
...{
get
...{
return this.m_sSource;
}
}
public string StackTrace
...{
get
...{
return this.m_sStackTrace;
}
}
/**//// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
...{
base.Dispose(disposing);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace Tigerleq.Log
...{
public class LogInfo : LogBase
...{
// Fields
private string m_sInfo;
// Methods
public LogInfo()
...{
this.m_sInfo = null;
}
public LogInfo(string p_sInfo, string p_sAddMsg)
: base(p_sAddMsg)
...{
this.m_sInfo = null;
this.m_sInfo = p_sInfo.Trim();
}
// Properties
public string Info
...{
get
...{
return this.m_sInfo;
}
}
/**//// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
...{
base.Dispose(disposing);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
namespace Tigerleq.Log
...{
public class LogWarn : LogBase
...{
// Fields
private string m_sStackTrace;
private string m_sWarn;
// Methods
public LogWarn()
...{
this.m_sWarn = null;
this.m_sStackTrace = null;
}
public LogWarn(string p_sWarn, string p_sAddMsg)
: base(p_sAddMsg)
...{
this.m_sWarn = null;
this.m_sStackTrace = null;
this.m_sWarn = p_sWarn.Trim();
this.m_sStackTrace = new StackTrace().ToString();
}
// Properties
public string stackTrace
...{
get
...{
return this.m_sStackTrace;
}
}
public string Warn
...{
get
...{
return this.m_sWarn;
}
}
/**//// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
...{
base.Dispose(disposing);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Tigerleq.Log
...{
public class LogWrite
...{
// Methods
public LogWrite(string p_sDir, Exception p_ex)
: this(p_sDir, p_ex, "")
...{
}
public LogWrite(string p_sDir, Exception p_ex, string p_sAddMsg)
...{
LogErr err = new LogErr(p_ex, p_sAddMsg);
new LogOperate(p_sDir).Write(err);
}
public LogWrite(string p_sDir, string p_sLogType, string p_sLog)
: this(p_sDir, p_sLogType, p_sLog, "")
...{
}
public LogWrite(string p_sDir, string p_sLogType, string p_sLog, string p_sAddMsg)
...{
LogOperate operate = new LogOperate(p_sDir);
if (p_sLogType.Trim().ToLower().Equals("info"))
...{
LogInfo info = new LogInfo(p_sLog, p_sAddMsg);
operate.Write(info);
}
else
...{
LogWarn warn = new LogWarn(p_sLog, p_sAddMsg);
operate.Write(warn);
}
}
}
}
产生的日志文件
效果为
<LogInfo>
<Time>2008-05-08 01:00:01</Time>
<ProcessID>864</ProcessID>
<ThreadID>816</ThreadID>
<AddMsg />
<Info>开始将服务加载到内存</Info>
</LogInfo>
<LogErr>
<Time>2008-05-08 01:00:01</Time>
<ProcessID>864</ProcessID>
<ThreadID>816</ThreadID>
<AddMsg>p_sAddMsg</AddMsg>
<Message>未能找到路径“E:代码资料C#Tiger'sControlLibraryWindowsServiceinDebugConfigServerConfig.xml”的一部分。</Message>
<ExceptionStackTrace> 在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
在 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
在 System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
在 System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
在 System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
在 System.Threading.CompressedStack.runTryCode(Object userData)
在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
在 System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
在 System.Xml.XmlTextReaderImpl.OpenUrl()
在 System.Xml.XmlTextReaderImpl.Read()
在 System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
在 System.Xml.XmlDocument.Load(XmlReader reader)
在 System.Xml.XmlDocument.Load(String filename)
在 Tigerleq.ServerConfig.ServerParas..ctor(String p_sFile) 位置 E:代码资料C#Tiger'sControlLibraryTiger'sClassLibraryServerConfigServerParas.cs:行号 49</ExceptionStackTrace>
<ExceptionStr>System.IO.DirectoryNotFoundException: 未能找到路径“E:代码资料C#Tiger'sControlLibraryWindowsServiceinDebugConfigServerConfig.xml”的一部分。
在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
在 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
在 System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
在 System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
在 System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
在 System.Threading.CompressedStack.runTryCode(Object userData)
在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
在 System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
在 System.Xml.XmlTextReaderImpl.OpenUrl()
在 System.Xml.XmlTextReaderImpl.Read()
在 System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
在 System.Xml.XmlDocument.Load(XmlReader reader)
在 System.Xml.XmlDocument.Load(String filename)
在 Tigerleq.ServerConfig.ServerParas..ctor(String p_sFile) 位置 E:代码资料C#Tiger'sControlLibraryTiger'sClassLibraryServerConfigServerParas.cs:行号 49</ExceptionStr>
<Source>mscorlib</Source>
<StackTrace> 在 Tigerleq.Log.LogErr..ctor(Exception p_ex, String p_sAddMsg)
在 Tigerleq.Log.LogOperate.OperateExp(Exception p_ex, String p_sAddMsg, String p_sShowMsg)
在 Tigerleq.ServerConfig.ServerParas..ctor(String p_sFile)
在 WindowsService.MainService..ctor()
在 WindowsService.Program.Main(String[] args)
</StackTrace>
</LogErr>
相关文章推荐
- 使用Spring.NET统一ASP.NET异常处理并记录日志
- Asp.Net : 捕捉和记录网站中出现的所有未处理错误,抛出详细的页面来源和访问ip,调用的接口方法及异常实例(记事本日志,系统日志及数据库日志)
- RDIFramework.NET — 基于.NET的快速信息化系统开发框架- 5.4平台日志、异常管理、生成自动升级配置文件模块
- RDIFramework.NET — 基于.NET的快速信息化系统开发框架- 5.4平台日志、异常管理、生成自动升级配置文件模块
- ASP.NET全局错误处理和异常日志记录以及IIS配置自定义错误页面
- 没头没尾--项目开发笔记:异常处理与日志记录代码自动生成(工具能生成多少代码!?续一)
- asp.net中的日志添加和未处理异常的记录
- ASP.NET Core 异常处理与日志记录
- Android中处理崩溃异常和记录日志
- Spring-Boot--日志操作【全局异常捕获消息处理☞日志控制台输出+日志文件记录】
- 使用Application_Error事件处理程序把异常记录到系统事件日志
- ASP.NET MVC 全局异常处理与异常日志
- Elmah .net 最方便最好用的日志,异常记录插件
- ASP.NET 4.0 生成 eurl.axd Http异常错误的处理方法
- Android中处理崩溃异常和记录日志
- 说说asp.net中的异常处理和日志追踪
- 我在项目中Springmvc处理异常并记录日志(一) ps:如何有更好的方法,请写到评论中多多交流,谢谢!
- Android 中处理崩溃异常和记录日志
- IT第二十天 - 面向对象编程思想、抽象类、异常处理、程序操作日志记录、本周总结 ★★★
- 在 ASP.NET 中用匿名委托简单模拟 AOP 做异常和日志处理