.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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对你的问题,我可以给出以下回答: 在 .NET Framework 4.7.2 中,可以使用 Microsoft.Extensions.Configuration 来管理应用程序的配置信息。这个框架提供了一些类,可以从多种不同的配置源(如 JSON、XML、命令行参数等)中读取配置信息,并将其统一封装成一个 IConfiguration 对象,供应用程序使用。 下面是一个简单的示例,演示如何使用 Microsoft.Extensions.Configuration 读取一个名为 appsettings.json 的配置文件: 1. 首先,在项目中添加 Microsoft.Extensions.Configuration 和 Microsoft.Extensions.Configuration.Json 包。 2. 在 appsettings.json 文件中定义需要读取的配置项,例如: ``` { "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } } } ``` 3. 在代码中读取配置项,例如: ``` using System.Configuration; using Microsoft.Extensions.Configuration; ... var builder = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); var connectionString = configuration.GetConnectionString("DefaultConnection"); var logLevel = configuration["Logging:LogLevel:Default"]; ``` 这里的代码首先创建了一个 ConfigurationBuilder 对象,并通过 AddJsonFile 方法指定要读取的配置文件的路径和名称。然后,调用 Build 方法创建了一个 IConfigurationRoot 对象,该对象表示了整个配置文件的内容。最后,可以通过 GetConnectionString 和索引器等方法获取需要的配置项。 希望这个回答对你有所帮助。如果你还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值