.net Core Api 注入 Microsoft.Extensions.Logging

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值