Пример #1
0
        public void FormatLogEntry()
        {
            LogEntry logEntry = CommonUtil.CreateLogEntry();
            string   xml      = xmlLogFormatter.Format(logEntry);

            Assert.IsFalse(string.IsNullOrEmpty(xml));
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xml);
            Assert.IsNotNull(xmlDocument.FirstChild);
        }
Пример #2
0
        public void Custom(string text)
        {
            var logEvent = new LogEvent(LogLevel.Custom, text);

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(LogFormatter.Format(logEvent));
        }
Пример #3
0
 private void SecureAppend(ILogEvent logEvent)
 {
     if (BuildFile())
     {
         CleanWriter();
     }
     // TODO: Remove this file access to improve performance
     // TODO: Count bytes written in memory instead.
     // TODO: Maybe use a wrapper class above writer and file
     _file.Refresh();
     if (_file.Exists && _file.Length > MaxLength)
     {
         CleanWriter();
         RollFiles();
     }
     if (_writer == null)
     {
         try
         {
             BuildWriter();
         }
         catch (Exception e) when(e is IOException || e is UnauthorizedAccessException)
         {
             _locked = true;
             BuildFile();
             BuildWriter();
         }
     }
     _writer.WriteLine(_logFormatter.Format(_provider, logEvent));
 }
Пример #4
0
        private async Task WriteLogsAsync(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                if (eventsQueue.IsEmpty)
                {
                    await Task.Delay(1000, token).ConfigureAwait(false);
                }
                else
                {
                    var fileName = GetFileName(DateTime.Now);

                    if (!System.IO.File.Exists(fileName))
                    {
                        System.IO.File.Create(fileName);
                    }

                    await using var writer = new StreamWriter(fileName, true);
                    {
                        while (eventsQueue.TryDequeue(out var logEvent))
                        {
                            await writer.WriteLineAsync(LogFormatter.Format(logEvent));
                        }
                    }
                }
            }
        }
Пример #5
0
 /// <summary>
 ///     Appends the specified log event.
 /// </summary>
 /// <param name="logEvent">The log event.</param>
 public void Append(ILogEvent logEvent)
 {
     if (_writer == null)
     {
         _writer           = _factory.CreateStreamWriter(_file);
         _writer.AutoFlush = true;
     }
     _writer.WriteLine(_logFormatter.Format(_provider, logEvent));
 }
Пример #6
0
        public void PrintEntry(Severity severity, int code, string message)
        {
            ConsoleColor old_color = Console.ForegroundColor;

            Console.ForegroundColor = logScheme.GetColor(severity);

            Console.Error.WriteLine(LogFormatter.Format(severity, code, indentLevel, message));

            Console.ForegroundColor = old_color;
        }
Пример #7
0
        public void Info(string text)
        {
            if (!IsInfoEnabled)
            {
                return;
            }
            var logEvent = new LogEvent(LogLevel.Info, text);

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(LogFormatter.Format(logEvent));
        }
Пример #8
0
        public void Warn(string text)
        {
            if (!IsWarnEnabled)
            {
                return;
            }
            var logEvent = new LogEvent(LogLevel.Warning, text);

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(LogFormatter.Format(logEvent));
        }
Пример #9
0
        public void Debug(string text)
        {
            if (!IsDebugEnabled)
            {
                return;
            }
            var logEvent = new LogEvent(LogLevel.Debug, text);

            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine(LogFormatter.Format(logEvent));
        }
Пример #10
0
        public void Error(string text)
        {
            if (!IsErrorEnabled)
            {
                return;
            }
            var logEvent = new LogEvent(LogLevel.Error, text);

            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine(LogFormatter.Format(logEvent));
        }
Пример #11
0
        public void Error(string text, Exception exception)
        {
            if (!IsErrorEnabled)
            {
                return;
            }
            var logEvent = new LogEvent(LogLevel.Error, $"{text} {exception.Message}");

            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine(LogFormatter.Format(logEvent));
        }
Пример #12
0
        public void Fatal(string text)
        {
            if (!IsFatalEnabled)
            {
                return;
            }
            var logEvent = new LogEvent(LogLevel.Fatal, text);

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(LogFormatter.Format(logEvent));
        }
Пример #13
0
        /// <summary>
        ///     Appends the specified log event.
        /// </summary>
        /// <param name="logEvent">The log event.</param>
        public void Append(ILogEvent logEvent)
        {
            var color   = GetColor(logEvent);
            var message = _formatter.Format(_provider, logEvent);

            _console.SafeCall(c =>
            {
                var foreground    = c.ForegroundColor;
                c.ForegroundColor = color;
                c.WriteLine(message);
                c.ForegroundColor = foreground;
            });
        }
Пример #14
0
        public override void Append(LogEvent Event)
        {
            switch (Event.Level)
            {
            case LogLevel.Error:
            case LogLevel.Fatal:
#if UNITY_EDITOR
                LiteFramework.Helper.UnityHelper.ShowEditorNotification(LogFormatter.Format(Event));
#endif
                break;

            default:
                break;
            }
        }
Пример #15
0
 public void CanFormatLogEntryWithExtendedProperties()
 {
     LogEntry logEntry = new LogEntry();
     logEntry.Message = "Hello";
     logEntry.Categories.Add("General");
     logEntry.ExtendedProperties.Add("test", "test");
     string xml = xmlLogFormatter.Format(logEntry);
     XmlDocument dom = new XmlDocument();
     dom.LoadXml(xml);
 }
Пример #16
0
        public static void test3()
        {
            LogEntry le = new LogEntry();

            le.Message   = "test";
            le.LogLevel  = LogLevel.Critical;
            le.Timestamp = Convert.ToDateTime("02/17/2018 22:00:12");
            le.Category  = "category";

            LogFormatter lf = new LogFormatter();

            lf.FormatSpecification = null;

            System.Console.WriteLine(lf.Format(le));
            //[2/18/2018 4:00:12 AM][Critical][category] test
        }
Пример #17
0
        public void Format_logFormatter_FormatSpecification_isNull()
        {
            LogEntry le = new LogEntry();

            le.Message   = "test";
            le.LogLevel  = LogLevel.Critical;
            le.Timestamp = Convert.ToDateTime("02/17/2018 22:00:12");
            le.Category  = "category";

            LogFormatter lf = new LogFormatter();

            lf.FormatSpecification = null;

            string result = "[2/18/2018 4:00:12 AM][Critical][category] test";

            Assert.AreEqual(result, lf.Format(le));
        }
Пример #18
0
        public void ToString_logentryformatiscorrect_returnstring_formatter()
        {
            LogEntry le = new LogEntry();

            le.Message   = "test";
            le.LogLevel  = LogLevel.Critical;
            le.Timestamp = Convert.ToDateTime("02/17/2018 22:00:12");
            le.Category  = "category";

            LogFormatter lf = new LogFormatter();

            lf.FormatSpecification = null;
            lf.Format(le);
            string result = "[2/18/2018 4:00:12 AM][Critical][category] test";

            Assert.AreEqual(result, le.ToString(lf));
        }
Пример #19
0
        public void PrintEntry(Severity severity, int code, string message)
        {
            if (textBox.TextLength != 0)
            {
                textBox.AppendText("\r\n");
            }

            textBox.SelectionBullet = true;
            textBox.BulletIndent    = 10;
            if (!SystemInformation.HighContrast)
            {
                textBox.SelectionColor = logColors[(int)severity];
            }

            textBox.AppendText(LogFormatter.Format(severity, code, indentLevel, message));
            textBox.AppendText("\r\n");

            textBox.SelectionBullet = false;
        }
Пример #20
0
        public override void Append(LogEvent Event)
        {
            switch (Event.Level)
            {
            case LogLevel.Info:
                Debug.Log(LogFormatter.Format(Event));
                break;

            case LogLevel.Warning:
                Debug.LogWarning(LogFormatter.Format(Event));
                break;

            case LogLevel.Error:
                Debug.LogError(LogFormatter.Format(Event));
                break;

            case LogLevel.Fatal:
                Debug.LogAssertion(LogFormatter.Format(Event));
                break;

            default:
                break;
            }
        }
Пример #21
0
 public override string ToString() => LogFormatter.Format(new object[]
 {
     nameof(Zip), Zip,
     nameof(Latitude), Latitude.ToString("F8"),
     nameof(Longitude), Longitude.ToString("F8")
 });
Пример #22
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, methods: "get")]
            HttpRequest req,
            [Inject] IContactService _contactService,
            [Inject] IEntitlementContactRoleService _entitlementContactRoleService,
            [Inject] IEntitlementService _entitlementService,
            [Inject] IAccountService _accountService,
            [Inject] IHttpClientFactory _httpClientFactory,
            [Inject] ISecretService _secretService,
            ILogger log,                             //default logger
            ExecutionContext context
            )
        {
            var onlyEnabled = true;
            var _httpClient = _httpClientFactory.CreateClient("Dynamics365");

            //Logging
            var storageAccountKey       = _secretService.GetSecretAsync("PortalLogsStorage-StorageAccountKey").Result.Value;
            var storageAccountName      = _secretService.GetSecretAsync("PortalLogsStorage-StorageAccountName").Result.Value;
            var storageAccountTableName = _secretService.GetSecretAsync("PortalLogs-TableName").Result.Value;
            var _customLogger           = new Logging.Service.LogService(new LoggingOptions
            {
                LogLevel           = LogLevel.Information,
                StorageAccountKey  = storageAccountKey,
                StorageAccountName = storageAccountName,
                TableName          = storageAccountTableName
            });

            try
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                log.LogInformation("Iniciar function.");

                log.LogInformation("Pegar token.");
                var _dynamicsTokenService = ConfigureDynamicsTokenService(_httpClient, req, config["KeyVaultBaseUrl"], config["InstanceDynamics"], new Guid(config["KeyVaultClientId"]), config["KeyVaultClientSecret"]);
                var token = await _dynamicsTokenService.GetAccessTokenAsync();

                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                string email = req.Query["email"];

                log.LogInformation("Pegar contato.");
                Domain.Entities.DynamicsContact contact;
                dynamic jsonObject = new JObject();
                jsonObject.Add("ResultState", "Success");
                jsonObject.Add("ErrorMessage", "");

                try
                {
                    contact = await _contactService.GetByMailAsync(_httpClient, email, config["InstanceDynamics"], onlyEnabled);

                    jsonObject["IdContact"] = contact.contactid;
                }
                catch (KeyNotFoundException ex)
                {
                    //Armazena log no table storage
                    var logState = new LogState("AzureFunctionDynamics", Guid.NewGuid(), null);
                    _customLogger.LogError(LogFormatter.Format(logState, ex));

                    jsonObject["ResultState"]  = "Failed";
                    jsonObject["ErrorMessage"] = "Usu�rio n�o cadastrado na organiza��o.";
                    return(new NotFoundObjectResult(jsonObject));
                }

                if (contact._parentcustomerid_value.HasValue)
                {
                    log.LogInformation("Pegar account number e parent account id.");
                    try
                    {
                        var account = await _accountService.GetByAccountIdAsync(_httpClient, contact._parentcustomerid_value?.ToString(), config["InstanceDynamics"], onlyEnabled);

                        jsonObject["AccountNumber"]          = account.accountnumber;
                        jsonObject["AccountId"]              = account.accountid;
                        jsonObject["AccountName"]            = account.name;
                        jsonObject["AccountCPNJ"]            = account.axt_cnpj;
                        jsonObject["AccountCPNJView"]        = account.axt_cnpjview;
                        jsonObject["AccountAxt_Razaosocial"] = account.axt_razaosocial;
                        if (account._parentaccountid_value.HasValue)
                        {
                            jsonObject["ParentAccountId"] = account._parentaccountid_value;
                        }
                        else
                        {
                            jsonObject["ParentAccountId"] = account.accountid;
                        }
                    }
                    catch (KeyNotFoundException ex)
                    {
                        //Armazena log no table storage
                        var logState = new LogState("AzureFunctionDynamics", Guid.NewGuid(), null);
                        _customLogger.LogError(LogFormatter.Format(logState, ex));

                        jsonObject["ResultState"]  = "Failed";
                        jsonObject["ErrorMessage"] = "Organiza��o n�o encontrada.";
                        return(new NotFoundObjectResult(jsonObject));
                    }
                }
                else
                {
                    jsonObject["AccountNumber"]                                  =
                        jsonObject["ParentAccountId"]                            =
                            jsonObject["AccountId"]                              =
                                jsonObject["AccountName"]                        =
                                    jsonObject["AccountCPNJ"]                    =
                                        jsonObject["AccountCPNJView"]            =
                                            jsonObject["AccountAxt_Razaosocial"] = null;
                }

                log.LogInformation("Pegar entitlementcontactrole.");
                try
                {
                    var entitlementContactRoles = await _entitlementContactRoleService.GetByContactIdAsync(_httpClient, contact.contactid.ToString(), config["InstanceDynamics"], onlyEnabled);

                    var arrayResult = new List <ContactData>();

                    foreach (var entry in entitlementContactRoles)
                    {
                        try
                        {
                            var entitlement = await _entitlementService.GetByEntitlementIdAsync(_httpClient, entry._axt_entitlementid_value.ToString(), config["InstanceDynamics"], onlyEnabled);

                            var aux = new ContactData
                            {
                                IdAccount     = entitlement._customerid_value,
                                IdServiceLine = entitlement._axt_servicelineid_value,
                                IdAxtRole     = entry.axt_role,
                                IdEntitlement = entitlement.entitlementid,
                                AxtName       = entry.axt_name
                            };
                            arrayResult.Add(aux);
                        }
                        catch (KeyNotFoundException)
                        {
                        }
                    }

                    jsonObject["Entries"] = JToken.FromObject(arrayResult);
                }
                catch (KeyNotFoundException ex)
                {
                    //Armazena log no table storage
                    var logState = new LogState("AzureFunctionDynamics", Guid.NewGuid(), null);
                    _customLogger.LogError(LogFormatter.Format(logState, ex));

                    jsonObject["ResultState"]  = "Failed";
                    jsonObject["ErrorMessage"] = "Usu�rio n�o cont�m perfil de acesso.";
                    return(new NotFoundObjectResult(jsonObject));
                }

                return(new OkObjectResult(jsonObject));
            }
            catch (Exception ex)
            {
                //Armazena log no table storage
                var logState = new LogState("AzureFunctionDynamics", Guid.NewGuid(), null);
                _customLogger.LogError(LogFormatter.Format(logState, ex));

                log.LogError(ex.Message);
                log.LogError(ex.StackTrace);
                return(new BadRequestResult());
            }
        }
Пример #23
0
 private string Format(params object[] kvp)
 {
     return(LogFormatter.Format(kvp));
 }
Пример #24
0
 protected override void InnerLog(LogEvent logEvent)
 {
     System.Console.ForegroundColor = GetColor(logEvent.Level);
     System.Console.WriteLine(LogFormatter.Format(logEvent));
 }
Пример #25
0
 public void PrintEntry(Severity severity, int code, string message)
 {
     writer.WriteLine(LogFormatter.Format(severity, code, indentLevel, message));
 }
Пример #26
0
 protected override void Log(LogEvent logEvent)
 {
     writer.WriteLine(LogFormatter.Format(logEvent));
 }
Пример #27
0
 /// <summary>
 ///     Appends the specified log event.
 /// </summary>
 /// <param name="logEvent">The log event.</param>
 public void Append(ILogEvent logEvent)
 {
     _wrapper.WriteLine(_formatter.Format(DefaultLogFormatProvider.Instance, logEvent));
 }
Пример #28
0
        protected override void Log(LogEvent logEvent)
        {
            var text = LogFormatter.Format(logEvent);

            Console.WriteLine(text);
        }