📄 applicationlog.cs
字号:
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace jianshiFile
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
public class ApplicationLog
{
//This object is added as a debug listener.
private static StreamWriter debugWriter;
public static String FormatException(Exception ex, String catchInfo)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append("基本内容:");
if (catchInfo != String.Empty)
{
strBuilder.Append(catchInfo).Append("\r\n");
}
strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace).Append("\r\n").Append(DateTime.Now.ToString()).Append("\r\n\r\n");
return strBuilder.ToString();
}
public static void WriteLog( Exception ex, String catchInfo)
{
WriteLog(FormatException( ex, catchInfo));
}
/// <summary>
/// Determine where a string needs to be written based on the
/// configuration settings and the error level.
/// <param name="level">The severity of the information to be logged.</param>
/// <param name="messageText">The string to be logged.</param>
/// </summary>
public static void WriteLog( String messageText)
{
//
// Be very careful by putting a Try/Catch around the entire routine.
// We should never throw an exception while logging.
//
try
{
//
// Write the message to the trace file
//
//Make sure a tracing file is specified.
if (debugWriter != null)
{
lock(debugWriter)
{
//写入Log文件
Debug.WriteLine(messageText);
debugWriter.Flush();
//显示到屏幕
Trace.WriteLine(messageText);
Trace.Flush();
}
}
}
catch {} //Ignore any exceptions.
}
static ApplicationLog()
{
//Protect thread locks with Try/Catch to guarantee that we let go of the lock.
try
{
//See if there is a debug configuration file specified and set up the
// tracing variables.
bool clearSettings = true;
try
{
String tracingFile = System.Configuration.ConfigurationSettings.AppSettings.GetValues("TracingTraceFile")[0].ToString();
FileInfo file = new FileInfo(tracingFile);
debugWriter = new StreamWriter(file.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
Debug.Listeners.Add(new TextWriterTraceListener(debugWriter));
TextWriterTraceListener consoleWriter = new
TextWriterTraceListener(System.Console.Out);
Trace.Listeners.Add(consoleWriter);
clearSettings = false;
}
catch
{
//Ignore the error
}
//Use default (empty) values if something went wrong
if (clearSettings)
{
debugWriter = null;
}
}
finally
{
//Remove the lock from the class object
//Monitor.Exit(myType);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -