[fix]修正UdpServer在接收广播时连续启动接收的错误,在StarAgent中,此时可能收到广播包,SocketFlags是Broadcast,需要清空,否则报错“参考的对象类型不支持尝试的操作”; 无需设置SocketOptionName.PacketInformation,在ReceiveMessageFromAsync时会自动设置,并且支持ipv6;
石头 authored at 2024-10-10 00:36:00 石头 committed at 2024-10-10 00:45:43
2.11 KiB
X
using System;
using System.Collections.Concurrent;

namespace NewLife.Log;

/// <summary>控制台输出日志</summary>
public class ConsoleLog : Logger
{
    /// <summary>是否使用多种颜色,默认使用</summary>
    public Boolean UseColor { get; set; } = true;

    /// <summary>写日志</summary>
    /// <param name="level"></param>
    /// <param name="format"></param>
    /// <param name="args"></param>
    protected override void OnWrite(LogLevel level, String format, params Object?[] args)
    {
        // 吃掉异常,避免应用崩溃
        try
        {
            var e = WriteLogEventArgs.Current.Set(level).Set(Format(format, args), null);

            if (!UseColor)
            {
                Console.WriteLine(e.GetAndReset());
                return;
            }

            lock (this)
            {
                var cc = Console.ForegroundColor;
                cc = level switch
                {
                    LogLevel.Warn => ConsoleColor.Yellow,
                    LogLevel.Error or LogLevel.Fatal => ConsoleColor.Red,
                    _ => GetColor(e.ThreadID),
                };
                var old = Console.ForegroundColor;
                Console.ForegroundColor = cc;
                Console.WriteLine(e.GetAndReset());
                Console.ForegroundColor = old;
            }
        }
        catch { }
    }

    static readonly ConcurrentDictionary<Int32, ConsoleColor> dic = new();
    static readonly ConsoleColor[] colors = [
        ConsoleColor.Green, ConsoleColor.Cyan, ConsoleColor.Magenta, ConsoleColor.White, ConsoleColor.Yellow,
        ConsoleColor.DarkGreen, ConsoleColor.DarkCyan, ConsoleColor.DarkMagenta, ConsoleColor.DarkRed, ConsoleColor.DarkYellow ];
    private static ConsoleColor GetColor(Int32 threadid)
    {
        if (threadid == 1) return ConsoleColor.Gray;

        return dic.GetOrAdd(threadid, k => colors[k % colors.Length]);
    }

    /// <summary>已重载。</summary>
    /// <returns></returns>
    public override String ToString() => $"{GetType().Name} UseColor={UseColor}";
}