首页 > 其他分享 >.net Core Api 注入 Microsoft.Extensions.Logging

.net Core Api 注入 Microsoft.Extensions.Logging

时间:2023-07-05 11:33:06浏览次数:29  
标签:Core object Logging string args Api using message logger

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();

 

标签:Core,object,Logging,string,args,Api,using,message,logger
From: https://www.cnblogs.com/hofmann/p/17528103.html

相关文章

  • .net Core Winform 增加NLog
    nlog.config<?xmlversion="1.0"encoding="utf-8"?><nlogxmlns="http://www.nlog-project.org/schemas/NLog.xsd"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><targetsasync=&quo......
  • .net Core API 添加 NLog
    nlog.config<?xmlversion="1.0"encoding="utf-8"?><nlogxmlns="http://www.nlog-project.org/schemas/NLog.xsd"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"autoReload="true"......
  • RunnerGo 新增对WebSocket、dubbo、TCP/IP三种协议的API测试
    大家好,RunnerGo作为一款一站式测试平台不断为用户提供更好的使用体验,最近得知RunnerGo新增对,WebSocket、Dubbo、TCP/IP,三种协议API的测试支持,本篇文章跟大家分享一下使用方法。WebSocket协议WebSocket是一种在单个TCP连接上进行全双工通信的API技术。相比于传统的HTTP......
  • Apipost IDEA插件新升级,Apipost Helper上架IDEA插件市场
    大家好!今天向大家介绍一个非常方便的IDEA插件——ApipostHelper!相信很多使用过Apipost的朋友在开发过程中都希望能够直接将编写好的API同步至Apipost,而无需手动填写。前段时间,Apipost推出了ApipostIDEA插件的内测版,我也亲自试用了一番,发现它非常实用。最近,也得知ApipostHelper......
  • historyApiFallback的解释
    historyApiFallback是一个webpack-dev-server的配置选项,用于解决使用HTML5HistoryAPI实现的前端路由在开发环境下的问题。它的原理是将没有匹配到静态文件的请求重定向到指定的HTML文件,通常是前端应用程序的入口文件。具体原理如下:当使用webpack-dev-server启动开发服务器时......
  • C#使用企业微信群聊机器人API
    publicclassOperationResult{publicboolIsSuccess{get;set;}publicintErrorCode{get;set;}publicstringContent{get;set;}}OperationResultinternalstaticclassTextType{internalst......
  • 从零到壹-API研发管理心得分享
    ❤️作者主页:小虚竹PC端左侧加我微信,进社群,有送书等更多活动!文章目录零、前言一、API研发管理1.1、什么是API研发管理1.2、痛点1.3、解决方案二、搭建部署及不同角色的关注点介绍2.1、下载安装2.2、开发管理创建项目及从第三方导入apiapi变更通知2.3、测试管理编写测试用例批量测试......
  • android 音标的抓取 腾讯在线词典API
       DICT.CN的webAPI已经close了,本想好,调用下接口把读音给抓下来。幸好,网上还是有好多的资源可以用的。昨天回去的时候,做了一个QQ的word抓音标的例子,还是大公司好,虽然非常的BS腾讯这狗抄袭人家的创意甚至是产品。 下面是几个开发的API测试了了是用于用的,但是你的程序中,文件......
  • asp.net core如何获取客户端IP地址
    客户端直接访问服务器直接通过HttpContext.Connection.RemoteIpAddress获取客户端Ip[HttpGet][Route("GetClientIP")]publicasyncTask<IActionResult>GetClientIP(){ varip4=HttpContext.Connection.RemoteIpAddress.MapToIPv4(); returnOk(ip4.ToString());}客......
  • 利用身份验证和授权机制,例如OAuth、JWT 和 API 密钥,APIaaS 如何帮助解决安全挑战?
    什么是APIaaS?APIaaS,即API即服务(APIasaService)是一种创新的基于云的方法,提供API(应用程序编程接口),使第三方服务提供商能够访问特定服务、数据或资源。它通过抽象内部API的复杂性,简化了开发、部署和管理API的过程。其主要目标是使开发人员和企业更容易地在其应用程序或软......