我已经在课堂下面实现了,它对我来说工作正常。另外,现在我不需要在app.config 文件中指定任何内容
class TextLogTraceListener : TextWriterTraceListener
{
private string logFileLocation = string.Empty;
private StreamWriter traceWriter;
public TextLogTraceListener(string filePath)
{
logFileLocation = filePath;
traceWriter = new StreamWriter(filePath, true);
traceWriter.AutoFlush = true;
}
public override void Write(string message)
{
traceWriter.Write(message);
}
public override void WriteLine(string message)
{
traceWriter.WriteLine(message);
}
public override void Close()
{
traceWriter.Close();
}
}
并像下面这样使用这个类:
public static class Logger
{
static TextLogTraceListener textLogTraceListener = new TextLogTraceListener("Trace.log");
public static void CloseWriter()
{
textLogTraceListener.Close();
}
public static void Error(string message, string module)
{
WriteEntry(message, "ERROR", module);
}
public static void Error(Exception ex, string module)
{
WriteEntry(ex.Message + Environment.NewLine + ex.StackTrace, "ERROR", module);
}
public static void Warning(string message, string module)
{
WriteEntry(message, "WARNING", module);
}
public static void Info(string message, string module)
{
WriteEntry(message, "INFO", module);
}
private static void WriteEntry(string message, string type, string module)
{
textLogTraceListener.WriteLine(string.Format("[{0}] [{1}] [{2}] {3}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
type,
module,
message));
}
}