.net日志操作类

早过忘川 提交于 2019-12-26 23:12:02

public class LogManager
{
    private static string logPath = string.Empty;
    /// <summary>
    /// 保存日志的文件夹
    /// </summary>
    public static string LogPath
    {
        get
        {
            if (logPath == string.Empty)
            {
                if (System.Web.HttpContext.Current == null)
                    // Windows Forms 应用
                    logPath = AppDomain.CurrentDomain.BaseDirectory;
                else
                    // Web 应用
                    logPath = AppDomain.CurrentDomain.BaseDirectory + @"bin\";
            }
            return logPath;
        }
        set{ logPath = value;}
    }

    private static string logFielPrefix = string.Empty;
    /// <summary>
    /// 日志文件前缀
    /// </summary>
    public static string LogFielPrefix
    {
        get { return logFielPrefix; }
        set { logFielPrefix = value; }
    }

    /// <summary>
    /// 写日志
    /// </summary>
    public static void WriteLog(string logFile, string msg)
    {
        try
        {
            System.IO.StreamWriter sw = System.IO.File.AppendText(
                LogPath + LogFielPrefix + logFile + " " +
                DateTime.Now.ToString("yyyyMMdd") + ".Log"
                );
            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + msg);
            sw.Close();
        }
        catch
        { }
    }

    /// <summary>
    /// 写日志
    /// </summary>
    public static void WriteLog(LogFile logFile, string msg)
    {
        WriteLog(logFile.ToString(), msg);
    }
}

/// <summary>
/// 日志类型
/// </summary>
public enum LogFile
{
    Trace,
    Warning,
    Error,
    SQL
}
文章来自学IT网:http://www.xueit.com/html/2009-04/21_1238_00.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!