日志工具

颜色和类别枚举:

EnumLogMsgColor

public enum EnumLogMsgColor
{
    Red,
    Green,
    Blue,
    Orange,
    Black,
}

EnumLogMsgLevel

public enum EnumLogMsgLevel
{
    /// <summary>
    /// 普通消息
    /// </summary>
    [Description("[普通日志]")] Info,

    /// <summary>
    /// 良好消息
    /// </summary>
    [Description("[良好日志]")] InfoGreen,

    /// <summary>
    /// 警告消息
    /// </summary>
    [Description("[警告日志]")] Warn,

    /// <summary>
    /// 异常消息
    /// </summary>
    [Description("[异常日志]")] Error,

    /// <summary>
    /// 清除消息
    /// </summary>
    [Description("[清除日志]")] Clear,
}

枚举扩展类EnumExtension

/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtension
{
    /// <summary>
    /// 获取描述
    /// </summary>
    /// <param name = "em"> </param>
    /// <returns> </returns>
    public static string GetDescription(this Enum em)
    {
        var type = em.GetType();
        var fd = type.GetField(em.ToString());
        if (fd == null)
        {
            return string.Empty;
        }

        var attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
        var name = string.Empty;
        foreach (DescriptionAttribute attr in attrs) name = attr.Description;

        return name;
    }
}

LogEventArgs

public class LogEventArgs : EventArgs
{
    /// <summary>
    /// 消息文本
    /// </summary>
    public string Msg { get; set; }

    /// <summary>
    /// 消息等级
    /// </summary>
    public EnumLogMsgLevel Level { get; set; } = EnumLogMsgLevel.Info;

    /// <summary>
    /// 消息颜色
    /// </summary>
    public EnumLogMsgColor Color { get; set; } = EnumLogMsgColor.Black;

    /// <summary>
    /// 获取画刷
    /// </summary>
    /// <returns> </returns>
    public Brush GetBrush()
    {
        Brush brush = null;
        switch (Color)
        {
            case EnumLogMsgColor.Red:
                brush = Brushes.Red;
                break;

            case EnumLogMsgColor.Green:
                brush = Brushes.Green;
                break;

            case EnumLogMsgColor.Blue:
                brush = Brushes.Blue;
                break;

            case EnumLogMsgColor.Orange:
                brush = Brushes.Orange;
                break;

            case EnumLogMsgColor.Black:
                brush = Brushes.Black;
                break;

            default:
                brush = Brushes.Black;
                break;
        }

        return brush;
    }
}

TXTFile

public class TXTFile
{
    /// <summary>
    /// 写入txt文件
    /// </summary>
    /// <param name = "absFilePath"> </param>
    /// <param name = "str"> </param>
    public void WriteTxtFile(string absFilePath, string str)
    {
        var path = new DirectoryInfo(absFilePath);
        if (path.Parent != null && !Directory.Exists(path.Parent.FullName))
        {
            Directory.CreateDirectory(path.Parent.FullName);
        }

        var mode = FileMode.Append;
        if (!File.Exists(absFilePath)) mode = FileMode.Create;

        using (var fs = new FileStream(absFilePath, mode))
        {
            using (var sw = new StreamWriter(fs, Encoding.Default))
            {
                sw.WriteLine(str);
            }
        }
    }
}

LogOperator

/// <summary>
/// 日志
/// </summary>
public class LogOperator
{
    #region 数据定义

    /// <summary>
    /// txt操作类
    /// </summary>
    protected static readonly TXTFile TXTFileOperator = new TXTFile();

    /// <summary>
    /// 异常日志定义
    /// </summary>
    private static readonly string INFO_PATH = Environment.CurrentDirectory + @"\Log\InfoLog\";

    /// <summary>
    /// 异常日志定义
    /// </summary>
    private static readonly string ERROR_PATH = Environment.CurrentDirectory + @"\Log\ErrorLog\";

    /// <summary>
    /// 警告日志定义
    /// </summary>
    private static readonly string WARN_PATH = Environment.CurrentDirectory + @"\Log\WarnLog\";

    #endregion

    #region 事件委托

    /// <summary>
    /// 委托
    /// </summary>
    /// <param name = "sender"> </param>
    /// <param name = "e"> </param>
    public delegate void LogContextChangeEventHandler(object sender, LogEventArgs e);

    /// <summary>
    /// 事件
    /// </summary>
    public static event LogContextChangeEventHandler LogContextChange;

    #endregion

    #region 日志操作

    /// <summary>
    /// 普通日志信息,不写入txt
    /// </summary>
    /// <param name = "msg"> </param>
    public static void Info(string msg)
    {
        var eventArgs = new LogEventArgs
        {
            Msg = msg,
            Level = EnumLogMsgLevel.Info,
            Color = EnumLogMsgColor.Black,
        };

        LogInvoke(eventArgs);
    }

    /// <summary>
    /// 普通日志信息-绿色
    /// </summary>
    /// <param name = "msg"> </param>
    public static void InfoGreen(string msg)
    {
        var eventArgs = new LogEventArgs
        {
            Msg = msg,
            Level = EnumLogMsgLevel.InfoGreen,
            Color = EnumLogMsgColor.Green,
        };

        TXTFileOperator.WriteTxtFile(GetInfoLogAbsPath(), DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "  " + eventArgs.Msg);

        LogInvoke(eventArgs);
    }

    /// <summary>
    /// 警告
    /// </summary>
    /// <param name = "msg"> </param>
    public static void Warn(string msg)
    {
        var eventArgs = new LogEventArgs
        {
            Msg = msg,
            Level = EnumLogMsgLevel.Warn,
            Color = EnumLogMsgColor.Orange,
        };

        TXTFileOperator.WriteTxtFile(GetWarnLogAbsPath(), DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "  " + eventArgs.Msg);

        LogInvoke(eventArgs);
    }

    /// <summary>
    /// 异常
    /// </summary>
    /// <param name = "msg"> </param>
    public static void Error(string msg)
    {
        var eventArgs = new LogEventArgs
        {
            Msg = msg,
            Level = EnumLogMsgLevel.Error,
            Color = EnumLogMsgColor.Red,
        };

        LogInvoke(eventArgs);

        TXTFileOperator.WriteTxtFile(GetErrorLogAbsPath(), eventArgs.Msg);
    }

    /// <summary>
    /// 清除所有日志信息
    /// </summary>
    public static void Clear()
    {
        var eventArgs = new LogEventArgs
        {
            Msg = "清除日志窗口",
            Level = EnumLogMsgLevel.Clear,
            Color = EnumLogMsgColor.Green,
        };

        LogContextChange?.Invoke(null, eventArgs);
    }

    /// <summary>
    /// 调用
    /// </summary>
    /// <param name = "eventArgs"> </param>
    protected static void LogInvoke(LogEventArgs eventArgs)
    {
        var msg = eventArgs.Level.GetDescription() + DateTime.Now + ":" + eventArgs.Msg;
        eventArgs.Msg = msg;
        LogContextChange?.Invoke(null, eventArgs);
    }

    /// <summary>
    /// 获取当前普通日志信息-绿色的绝对文件路径
    /// 当前日期命名
    /// </summary>
    /// <returns> </returns>
    protected static string GetInfoLogAbsPath()
    {
        var str = DateTime.Now.ToShortDateString();
        str = INFO_PATH + str.Replace('/', '_') + ".txt";
        return str;
    }

    /// <summary>
    /// 获取当前错误日志的绝对文件路径
    /// 当前日期命名
    /// </summary>
    /// <returns> </returns>
    protected static string GetErrorLogAbsPath()
    {
        var str = DateTime.Now.ToShortDateString();
        str = ERROR_PATH + str.Replace('/', '_') + ".txt";
        return str;
    }

    /// <summary>
    /// 警告日志
    /// </summary>
    /// <returns> </returns>
    protected static string GetWarnLogAbsPath()
    {
        var str = DateTime.Now.ToShortDateString();
        str = WARN_PATH + str.Replace('/', '_') + ".txt";
        return str;
    }

    #endregion
}

在ListBox里写日志,xaml后台代码,m_Log为ListBox名称

/// <summary>
/// 安全的日志信息
/// </summary>
/// <param name = "e"> </param>
protected void SafeAddMsg(LogEventArgs e)
{
    Dispatcher?.Invoke(() =>
    {
        var items = m_Log.Items;
        //清空
        if (e.Level == EnumLogMsgLevel.Clear)
        {
            items.Clear();
            return;
        }

        //增加时间显示
        var item = new TextBlock
        {
            Text = e.Msg,
            Foreground = e.GetBrush(),
        };

        if (items.Count > 50)
        {
            //移除首位
            items.RemoveAt(0);
        }

        items.Add(item);

        //滚动视图到最后一项
        var index = items.Count - 1;
        m_Log.SelectedIndex = index;
        var itemLast = m_Log.Items.GetItemAt(index);
        m_Log.ScrollIntoView(itemLast);
    });
}

/// <summary>
/// 窗口加载
/// </summary>
/// <param name = "sender"> </param>
/// <param name = "e"> </param>
private void MainLogFace_OnLoaded(object sender, RoutedEventArgs e)
{
    //m_Log.ItemsSource = LogOperator.LogSource;

    //注册日志消息变更事件
    LogOperator.LogContextChange -= OnLogContextChange;
    LogOperator.LogContextChange += OnLogContextChange;
}

/// <summary>
/// 日志事件
/// </summary>
/// <param name = "sender"> </param>
/// <param name = "e"> </param>
private void OnLogContextChange(object sender, LogEventArgs e)
{
    SafeAddMsg(e);
}

调用

LogOperator.Info("写到Listbox中,不产生日志");

LogOperator.InfoGreen("写到Listbox中,产生info日志");

LogOperator.Error("写到Listbox中,产生Error日志");

LogOperator.Warn("写到Listbox中,产生Warn日志");

 

posted @ 2024-01-24 15:39  时而有风  阅读(47)  评论(0编辑  收藏  举报