.net Core Api 注入 Microsoft.Extensions.Logging

发布时间 2023-07-05 11:38:15作者: hofmann

ILoggerAdapter.cs

using System;
using System.Collections.Generic;
using System.Text;
    public interface ILoggerAdapter<T>
    {
        //
        // Summary:
        //     Formats and writes an informational log message.
        //
        // Parameters:
        //   message:
        //     Format string of the log message in message template format. Example:
        //     "User {User} logged in from {Address}"
        //
        //   args:
        //     An object array that contains zero or more objects to format.
        void LogInformation(string message, params object[] args);

        void LogWarning(string message, params object[] args);
        void LogError(string message, params object[] args);
        void LogDebug(string message, params object[] args);

        void LogTrace(string message, params object[] args);
       
    }

LoggerAdapter.cs

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
internal class LoggerAdapter<T> : ILoggerAdapter<T>
    {
        private readonly ILogger<T> logger;

        public LoggerAdapter(ILogger<T> logger)
        {
            this.logger = logger;
        }

        public void LogDebug(string message, params object[] args)
        {
            try
            {
                if (logger.IsEnabled(LogLevel.Debug))
                {
                    string[] newArgs = GetNewArgs(args);
                    logger.LogDebug(DesensitizationMessage(message), newArgs);
                }
            }
            catch (Exception ex)
            {
                logger.LogDebug(message, args);
                logger.LogError("LogDebug Exception:" + ex.ToString());
            }
        }

        public void LogError(string message, params object[] args)
        {
            logger.LogError(message, args);
        }

        public void LogInformation(string message, params object[] args)
        {
            try
            {
                logger.LogInformation(DesensitizationMessage(message), GetNewArgs(args));
            }
            catch (Exception ex)
            {
                logger.LogInformation(message, args);
                logger.LogError("LogInformation Exception:" + ex.ToString());
            }
        }

        public void LogTrace(string message, params object[] args)
        {
            try
            {
                if (logger.IsEnabled(LogLevel.Trace))
                {
                    logger.LogTrace(DesensitizationMessage(message), GetNewArgs(args));
                }
            }
            catch (Exception ex)
            {
                logger.LogTrace(message, args);
                logger.LogError("LogTrace Exception:" + ex.ToString());
            }
        }
        public void LogWarning(string message, params object[] args)
        {
            logger.LogWarning(message, args);
        }

        private string[] GetNewArgs(object[] args)
        {
            string[] newArgs = null;
            if (args != null)
            {
                newArgs = new string[args.Length];
                for (int i = 0; i < args.Length; i++)
                {
                    newArgs[i] = DesensitizationMessage(args[i].ToString());
                }
            }
            return newArgs;
        }

        private string DesensitizationMessage(string message)
        {
            string newMessage = message;
            Dictionary<string, string> replacementDic = new Dictionary<string, string>();
            List<string> regExpresses = new List<string>();
            regExpresses.Add("\"[aA]pplicant[nN]ame\": {0,10}\"?(.[^,\"]{1,30})\"?,");
            regExpresses.Add("\"[iI]dentify[nN]umber\": {0,10}\"?(.[^,\"]{1,30})\"?,");
            regExpresses.Add("\"[mM]obile[pP]hone\": {0,10}\"?(.[^,\"]{1,30})\"?,");
            foreach (string regExp in regExpresses)
            {
                var Matches = Regex.Matches(message, regExp);
                if (Matches.Count > 0)
                {
                    foreach (Match Match in Matches)
                    {
                        if (Match.Success && !replacementDic.ContainsKey(Match.Groups[0].Value))
                        {
                            replacementDic.Add(Match.Groups[0].Value, DesensiKeyword(Match.Groups[1].Value, Match.Groups[0].Value));
                        }
                    }
                }
            }
            if (replacementDic.Count > 0)
            {
                foreach (KeyValuePair<string, string> kv in replacementDic)
                {
                    newMessage = newMessage.Replace(kv.Key, kv.Value);
                }
            }
            return newMessage;
        }

        private string DesensiKeyword(string keyword, string message)
        {
            string star = "*****";
            int keyLen = keyword.Length;
            string desKeyword = string.Empty;
            if (keyLen <= 1)
            {
                return message;
            }
            if (keyLen == 2)
            {
                desKeyword = keyword.Substring(0, 1) + star;
            }
            else
            {
                desKeyword = keyword.Substring(0, 1) + star + keyword.Substring(keyLen - 1);

            }
            return message.Replace(keyword, desKeyword);
        }
    }

LoggerAdapterExtensions.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Text;
public static class LoggerAdapterExtensions
    {
        public static void AddLoggerAdapter(this IServiceCollection services)
        {
            services.TryAdd(ServiceDescriptor.Singleton(typeof(ILoggerAdapter<>), typeof(LoggerAdapter<>)));
        }
    }

Startup.cs

services.AddLoggerAdapter();