Веб-API конфигурации Application Insights - PullRequest
1 голос
/ 25 февраля 2020

Я создал проект библиотеки для записи журналов в ApplicationInsights, а также в хранилище таблиц, и в настоящее время используется другими проектами WebAPI. Но по какой-то причине журналы не регистрируются в Application Insights, а работают с хранилищем таблиц.

private void AddTelemetryTarget(string instrumentationKey, LoggerEnumerations.LogLevel minLogLevel, LoggingConfiguration config)
        {
            try
            {           ConfigurationItemFactory.Default.Targets.RegisterDefinition("ApplicationInsightsTarget", typeof(ApplicationInsightsTarget));
                ApplicationInsightsTarget aiTarget = new ApplicationInsightsTarget();
                aiTarget.InstrumentationKey = instrumentationKey;
                aiTarget.Name = "ai";
                var wrapper = new AsyncTargetWrapper(aiTarget, 5000, AsyncTargetWrapperOverflowAction.Grow);
                config.AddTarget("TelemetryAsyncWrapper", wrapper);

                //Applying logging rules.
                LoggingRule rule = new LoggingRule("*", ConvertLogType(minLogLevel), aiTarget);
                config.LoggingRules.Add(rule);
            }
            catch
            { }
        }
        private LogLevel ConvertLogType(LoggerEnumerations.LogLevel type)
        {
            switch (type)
            {
                case LoggerEnumerations.LogLevel.Error: return LogLevel.Error;
                case LoggerEnumerations.LogLevel.Info: return LogLevel.Info;
                case LoggerEnumerations.LogLevel.Warn: return LogLevel.Warn;
                default: return LogLevel.Trace;
            }
        }


public async Task Log(string message, LoggerEnumerations.LogLevel type, Dictionary<string, string> customParams, Exception ex = null, bool isPayload = false)
        {
            LogEventInfo eventInfo = PopulateEventInfo(message, type, customParams, ex);
            if (!isPayload)
            {
                _logger.Log(eventInfo);
            }
            else
            {
                _payloadLogger.Log(eventInfo);
            }
        }

        private LogEventInfo PopulateEventInfo(string message, LoggerEnumerations.LogLevel type, Dictionary<string, string> customParams, Exception ex = null)
        {
            LogEventInfo eventInfo = new LogEventInfo();

            eventInfo.Level = ConvertLogType(type);
            eventInfo.Message = message;
            eventInfo.LoggerName = this.GetType().ToString();
            if (ex != null)
            {
                eventInfo.Exception = ex;
            }
            else if (eventInfo.Level == LogLevel.Error)
            {
                eventInfo.Exception = new Exception(message);
            }
            //Adding custom properties to LogEventInfo to display in Application insight 
            if (customParams != null)
            {
                foreach (KeyValuePair<string, string> param in customParams)
                {
                    eventInfo.Properties.Add(param.Key, param.Value);
                }
            }
            return eventInfo;
        }

Версии пакетов Nuget:

Microsoft.ApplicationInsights.NLogTarget: 2.13.1 NLog: 4.6.8

Спасибо

1 Ответ

1 голос
/ 22 марта 2020

Я добавил Application Insights в качестве подключенных служб и удалил инструментальный ключ из файла ApplicationInsights.config, и при регистрации цели nlog я использовал инструментальный ключ из моего файла web.config, и он начал работать.

...