代码改变世界

mylog

2022-09-14 00:01  qgbo  阅读(64)  评论(0)    收藏  举报

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var s = state as IEnumerable<KeyValuePair<string, object>>;

var messageTemplate = s?.LastOrDefault().Value.ToString();

var para = s?.Select(t => t.Value).ToArray();

var st = new StackTrace(0, true);

var fram = st.GetFrames();

var str = new StringBuilder();
foreach (var item in fram)
{
int lineNum = item.GetFileLineNumber();

str.AppendLine(item.GetFileName() +","+ lineNum.ToString());
}

 

using (LogContext.PushProperty("Name", str))
{
if (para.Count() == 1)
{ Serilog.Log.Logger.Write(LogEventLevel.Warning, messageTemplate); }
else if (para.Count() == 2)
{ Serilog.Log.Logger.Write(LogEventLevel.Warning, messageTemplate, para.First()); }
else if (para.Count() == 3)
{ Serilog.Log.Logger.Write(LogEventLevel.Warning, messageTemplate, para[0], para[1]); }
}

}

 

public static class MyEs
    {

        public static void myPrint(this Test test, [CallerFilePath]string  path = null)
        {
            Console.WriteLine("www"+ path);
        }


        public static LoggerConfiguration myElasticsearch(
            this LoggerSinkConfiguration loggerSinkConfiguration,
            string nodeUris,
            string indexFormat = null,
            string templateName = null,
            string typeName = "logevent",
            int batchPostingLimit = 50,
            int period = 2,
            bool inlineFields = false,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string bufferBaseFilename = null,
            long? bufferFileSizeLimitBytes = null,
            long bufferLogShippingInterval = 5000,
            string connectionGlobalHeaders = null,
            LoggingLevelSwitch levelSwitch = null,
            int connectionTimeout = 5,
            EmitEventFailureHandling emitEventFailure = EmitEventFailureHandling.WriteToSelfLog,
            int queueSizeLimit = 100000,
            string pipelineName = null,
            bool autoRegisterTemplate = false,
            AutoRegisterTemplateVersion autoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv2,
            bool overwriteTemplate = false,
            RegisterTemplateRecovery registerTemplateFailure = RegisterTemplateRecovery.IndexAnyway,
            string deadLetterIndexName = null,
            int? numberOfShards = null,
            int? numberOfReplicas = null,
            IFormatProvider formatProvider = null,
            IConnection connection = null,
            IElasticsearchSerializer serializer = null,
            IConnectionPool connectionPool = null,
            ITextFormatter customFormatter = null,
            ITextFormatter customDurableFormatter = null,
            ILogEventSink failureSink = null,
            long? singleEventSizePostingLimit = null,
            int? bufferFileCountLimit = null)
        {
            if (string.IsNullOrEmpty(nodeUris))
                throw new ArgumentNullException(nameof(nodeUris), "No Elasticsearch node(s) specified.");

            IEnumerable<Uri> nodes = nodeUris
                .Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(uriString => new Uri(uriString));

            var options = connectionPool == null ? new ElasticsearchSinkOptions(nodes) : new ElasticsearchSinkOptions(connectionPool);

            if (!string.IsNullOrWhiteSpace(indexFormat))
            {
                options.IndexFormat = indexFormat;
            }

            if (!string.IsNullOrWhiteSpace(templateName))
            {
                options.AutoRegisterTemplate = true;
                options.TemplateName = templateName;
            }

            options.TypeName = !string.IsNullOrWhiteSpace(typeName) ? typeName : null;

            options.BatchPostingLimit = batchPostingLimit;
            options.SingleEventSizePostingLimit = singleEventSizePostingLimit;
            options.Period = TimeSpan.FromSeconds(period);
            options.InlineFields = inlineFields;
            options.MinimumLogEventLevel = restrictedToMinimumLevel;
            options.LevelSwitch = levelSwitch;

            if (!string.IsNullOrWhiteSpace(bufferBaseFilename))
            {
                Path.GetFullPath(bufferBaseFilename);       // validate path
                options.BufferBaseFilename = bufferBaseFilename;
            }

            if (bufferFileSizeLimitBytes.HasValue)
            {
                options.BufferFileSizeLimitBytes = bufferFileSizeLimitBytes.Value;
            }

            if (bufferFileCountLimit.HasValue)
            {
                options.BufferFileCountLimit = bufferFileCountLimit.Value;
            }
            options.BufferLogShippingInterval = TimeSpan.FromMilliseconds(bufferLogShippingInterval);

            if (!string.IsNullOrWhiteSpace(connectionGlobalHeaders))
            {
                NameValueCollection headers = new NameValueCollection();
                connectionGlobalHeaders
                    .Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)
                    .ToList()
                    .ForEach(headerValueStr =>
                    {
                        var headerValue = headerValueStr.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
                        headers.Add(headerValue[0], headerValue[1]);
                    });

                options.ModifyConnectionSettings = (c) => c.GlobalHeaders(headers);
            }

            options.ConnectionTimeout = TimeSpan.FromSeconds(connectionTimeout);
            options.EmitEventFailure = emitEventFailure;
            options.QueueSizeLimit = queueSizeLimit;
            options.PipelineName = pipelineName;

            options.AutoRegisterTemplate = autoRegisterTemplate;
            options.AutoRegisterTemplateVersion = autoRegisterTemplateVersion;
            options.RegisterTemplateFailure = registerTemplateFailure;
            options.OverwriteTemplate = overwriteTemplate;
            options.NumberOfShards = numberOfShards;
            options.NumberOfReplicas = numberOfReplicas;

            if (!string.IsNullOrWhiteSpace(deadLetterIndexName))
            {
                options.DeadLetterIndexName = deadLetterIndexName;
            }

            options.FormatProvider = formatProvider;
            options.FailureSink = failureSink;
            options.Connection = connection;
            options.CustomFormatter = customFormatter;
            options.CustomDurableFormatter = customDurableFormatter;
            options.Serializer = serializer;

            options.FailureCallback = e =>
            {
                Console.WriteLine(e);
            };

            return loggerSinkConfiguration.Elasticsearch(options);
        }
    }