C#为记录器类正确实现StreamWriter

我的项目遇到了一个奇怪的问题。

这是我的记录器类:

using System.Diagnostics;
using System.IO;

namespace someSpace
{
    public enum LogTarget
    {
        File, Database, EventLog
    }

    public static class LogHelper
    {
        private static LogBase logger = null;
        public static void Log(LogTarget target, string path, string message)
        {
            switch (target)
            {
                case LogTarget.File:
                    logger = new FileLogger();
                    logger.Log(path, message);
                    break;
                case LogTarget.EventLog:
                    logger = new EventLogger();
                    logger.Log("", message);
                    break;
                default:
                    return;
            }
        }
    }

    public abstract class LogBase
    {
        protected readonly object lockObj = new object();
        public abstract void Log(string path, string message);
    }

    public class FileLogger : LogBase
    {
        public override void Log(string path, string message)
        {
            lock (lockObj)
            {
                File.Open(path, FileMode.Open).Close();
                using (StreamWriter streamWriter = new StreamWriter(path))
                {
                    streamWriter.WriteLine(message);
                    streamWriter.Close();
                }
            }
        }
    }

    public class EventLogger : LogBase
    {
        public override void Log(string path, string message)
        {
            lock (lockObj)
            {
                EventLog m_EventLog = new EventLog("");
                m_EventLog.Source = "IDGEventLog";
                m_EventLog.WriteEntry(message);
            }
        }
    } 
} 

我这样称呼日志功能...

LogHelper.Log(LogTarget.File, LOG_FILE_PATH, e.ToString());

我假设通过在类中使用“ using”结构,流将自动关闭,随后文件将被关闭并释放。

那不会发生;程序的后续运行一直说该文件仍在被某些进程使用。我不知道该怎么做才能诊断问题。

评论