Exemplo n.º 1
0
        /// <summary>
        /// The constructor used by ELMAH. ELMAH provides key/value pairs in the config dictionary,
        /// as specified in attributes in the ELMAH XML configuration (web.config).
        /// This constructor intentionally handles the internal ILogger instance as singleton.
        /// ELMAH calls this constructor one time per error logged and to only create the logger
        /// once, letting you listen for events on the logger etc., the logger needs to be
        /// singleton.
        /// </summary>
        public ErrorLog(IDictionary config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            _logId = config.LogId();
            var apiKey = config.ApiKey();

            ApplicationName = config.ApplicationName();

            if (Api != null)
            {
                return;
            }

            var url        = config.Url();
            var elmahioApi = ElmahioAPI.Create(apiKey);

            if (url != null)
            {
                elmahioApi.BaseUri = url;
            }

            Api = elmahioApi;
        }
Exemplo n.º 2
0
        protected override void Write(LogEventInfo logEvent)
        {
            if (_client == null)
            {
                _client = ElmahioAPI.Create(ApiKey);
            }

            var title = Layout != null && Layout.ToString() != "'${longdate}|${level:uppercase=true}|${logger}|${message}'"
                ? Layout.Render(logEvent)
                : logEvent.FormattedMessage;

            var message = new CreateMessage
            {
                Title       = title,
                Severity    = LevelToSeverity(logEvent.Level),
                DateTime    = logEvent.TimeStamp.ToUniversalTime(),
                Detail      = logEvent.Exception?.ToString(),
                Data        = PropertiesToData(logEvent.Properties),
                Source      = logEvent.LoggerName,
                Hostname    = MachineName(logEvent),
                Application = Application,
                User        = User(logEvent),
            };

            _client.Messages.CreateAndNotify(new Guid(LogId), message);
        }
        public Task PublishAsync(HealthReport report, CancellationToken cancellationToken)
        {
            if (report.Status == HealthStatus.Healthy)
            {
                return(Task.CompletedTask);
            }

            var api = ElmahioAPI.Create(apiKey);

            api.Messages.OnMessageFail += Messages_OnMessageFail;
            api.Messages.OnMessage     += Messages_OnMessage;

            var firstErrorWithException = report
                                          .Entries
                                          .Values
                                          .OrderBy(v => v.Status)
                                          .Cast <HealthReportEntry?>()
                                          .FirstOrDefault(v => v.HasValue && v.Value.Exception != null);

            var msg = new CreateMessage
            {
                Title    = Title(report),
                Severity = Severity(report.Status),
                Detail   = Detail(report),
                DateTime = DateTime.UtcNow,
                Type     = firstErrorWithException?.Exception.GetBaseException().GetType().Name,
                Source   = firstErrorWithException?.Exception.GetBaseException().Source,
                Hostname = Environment.MachineName,
                Data     = Data(report),
            };

            var result = api.Messages.CreateAndNotify(logId, msg);

            return(Task.CompletedTask);
        }
Exemplo n.º 4
0
        void MyApp_UnhandledExceptionHandler(object sender, RaiseThrowableEventArgs e)
        {
            var packageInfo = PackageManager.GetPackageInfo(PackageName, PackageInfoFlags.MetaData);

            // Do your error handling here.

            if (api == null)
            {
                api = ElmahioAPI.Create("API_KEY");
            }

            var exception     = e.Exception;
            var baseException = exception?.GetBaseException();

            api.Messages.Create("LOG_ID", new CreateMessage
            {
                Data        = exception?.ToDataList(),
                DateTime    = DateTime.UtcNow,
                Detail      = exception?.ToString(),
                Severity    = "Error",
                Source      = baseException?.Source,
                Title       = baseException?.Message ?? "Unhandled Xamarin exception",
                Type        = baseException?.GetType().FullName,
                Version     = packageInfo.VersionName,
                Application = packageInfo.PackageName,
            });
        }
Exemplo n.º 5
0
 public async void OnActionExecuting(ActionExecutingContext context)
 {
     if (_hostingEnviroment.IsProduction())
     {
         var message = new CreateMessage
         {
             Version         = "v1.0",
             Application     = "KnowLedge.IO",
             Source          = "GlobalActionLoggerFilter",
             Hostname        = context.HttpContext.Request.Host.Host,
             Url             = context.HttpContext.Request.GetDisplayUrl(),
             DateTime        = DateTime.Now,
             Method          = context.HttpContext.Request.Method,
             StatusCode      = context.HttpContext.Response.StatusCode,
             ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
             Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Executando ação", Dados = context.ActionArguments.Values })
         };
         var usuario = context.HttpContext.User;
         if (usuario != null)
         {
             try
             {
                 message.User = usuario.Claims.FirstOrDefault(c => c.Type == "email").Value;
             }
             catch (Exception)
             {
             }
         }
         var client = ElmahioAPI.Create("daa07db41fff467f9a4cde8e96d8a5f5", _options.CurrentValue);
         await client.Messages.CreateAsync(new Guid("324d3dc7-d02e-44b1-92b2-c5f8ff17c741").ToString(), message);
     }
 }
Exemplo n.º 6
0
        public static void Ship(Exception exception, string title, HttpContext context, ElmahIoOptions options, IBackgroundTaskQueue queue)
        {
            var baseException = exception?.GetBaseException();
            var createMessage = new CreateMessage
            {
                DateTime        = DateTime.UtcNow,
                Detail          = Detail(exception, options),
                Type            = baseException?.GetType().FullName,
                Title           = title,
                Data            = exception?.ToDataList(),
                Cookies         = Cookies(context),
                Form            = Form(context),
                Hostname        = Hostname(context),
                ServerVariables = ServerVariables(context),
                StatusCode      = StatusCode(exception, context),
                Url             = Url(context),
                QueryString     = QueryString(context),
                Method          = context.Request?.Method,
                Severity        = Severity(exception, context),
                Source          = Source(baseException),
                Application     = options.Application,
            };

            TrySetUser(context, createMessage);

            if (options.OnFilter != null && options.OnFilter(createMessage))
            {
                return;
            }

            queue.QueueBackgroundWorkItem(async token =>
            {
                var elmahioApi = (ElmahioAPI)ElmahioAPI.Create(options.ApiKey, new Client.ElmahIoOptions
                {
                    WebProxy = options.WebProxy
                });
                // Storing the message is behind a queue why the default timeout of 5 seconds isn't needed here.
                elmahioApi.HttpClient.Timeout = new TimeSpan(0, 0, 30);
                elmahioApi.HttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("Elmah.Io.AspNetCore", _assemblyVersion)));

                elmahioApi.Messages.OnMessage += (sender, args) =>
                {
                    options.OnMessage?.Invoke(args.Message);
                };
                elmahioApi.Messages.OnMessageFail += (sender, args) =>
                {
                    options.OnError?.Invoke(args.Message, args.Error);
                };

                try
                {
                    await elmahioApi.Messages.CreateAndNotifyAsync(options.LogId, createMessage);
                }
                catch (Exception e)
                {
                    options.OnError?.Invoke(createMessage, e);
                    // If there's a Exception while generating the error page, re-throw the original exception.
                }
            });
        }
Exemplo n.º 7
0
        /// <summary>
        /// This method is called by Azure Functions when a function has been executed. It is not intended to be called manually.
        /// </summary>
#pragma warning disable CS0618 // Type or member is obsolete
        public async Task OnExecutedAsync(FunctionExecutedContext executedContext, CancellationToken cancellationToken)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            long?took = null;

            if (executedContext.Properties.ContainsKey(Constants.StopwatchKeyName))
            {
                var stopwatch = executedContext.Properties[Constants.StopwatchKeyName] as Stopwatch;
                if (stopwatch != null)
                {
                    stopwatch.Stop();
                    took = stopwatch.ElapsedMilliseconds;
                }
            }

            if (api == null)
            {
                api = (ElmahioAPI)ElmahioAPI.Create(options.ApiKey, new ElmahIoOptions
                {
                    Timeout   = options.Timeout,
                    UserAgent = UserAgent(),
                });
            }

            if (executedContext.FunctionResult.Succeeded)
            {
                await api.Heartbeats.HealthyAsync(options.LogId, options.HeartbeatId, took : took);
            }
            else
            {
                await api.Heartbeats.UnhealthyAsync(options.LogId, options.HeartbeatId, executedContext.FunctionResult.Exception?.ToString(), took : took);
            }
        }
Exemplo n.º 8
0
 public ElmahIoLogger(string apiKey, Guid logId, ElmahIoProviderOptions options)
 {
     _logId      = logId;
     _elmahioApi = ElmahioAPI.Create(apiKey);
     _elmahioApi.Messages.OnMessage     += (sender, args) => options.OnMessage?.Invoke(args.Message);
     _elmahioApi.Messages.OnMessageFail += (sender, args) => options.OnError?.Invoke(args.Message, args.Error);
     _options = options;
 }
Exemplo n.º 9
0
        protected static ElmahioAPI Api(string apiKey)
        {
            var api = (ElmahioAPI)ElmahioAPI.Create(apiKey);

            api.HttpClient.Timeout = new TimeSpan(0, 1, 0);
            api.HttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("Elmah.Io.Cli", typeof(CommandBase).Assembly.GetName().Version.ToString())));
            return(api);
        }
Exemplo n.º 10
0
        public static async Task Ship(FunctionExceptionContext exceptionContext, HttpContext context, ElmahIoFunctionOptions options)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            var exception     = exceptionContext.Exception;
            var baseException = exception?.GetBaseException();
            var createMessage = new CreateMessage
            {
                DateTime        = DateTime.UtcNow,
                Detail          = Detail(exception),
                Type            = baseException?.GetType().FullName,
                Title           = baseException.Message,
                Data            = Data(exceptionContext),
                Cookies         = Cookies(context),
                Form            = Form(context),
                Hostname        = Hostname(context),
                ServerVariables = ServerVariables(context),
                StatusCode      = StatusCode(exception, context),
                Url             = context?.Request?.Path.Value,
                QueryString     = QueryString(context),
                Method          = context?.Request?.Method,
                Severity        = Severity(exception, context),
                Source          = Source(baseException),
                Application     = options.Application,
            };

            if (options.OnFilter != null && options.OnFilter(createMessage))
            {
                return;
            }

            if (elmahIoClient == null)
            {
                elmahIoClient = ElmahioAPI.Create(options.ApiKey, new ElmahIoOptions
                {
                    Timeout   = options.Timeout,
                    UserAgent = UserAgent(),
                });

                elmahIoClient.Messages.OnMessage += (sender, args) =>
                {
                    options.OnMessage?.Invoke(args.Message);
                };
                elmahIoClient.Messages.OnMessageFail += (sender, args) =>
                {
                    options.OnError?.Invoke(args.Message, args.Error);
                };
            }

            try
            {
                await elmahIoClient.Messages.CreateAndNotifyAsync(options.LogId, createMessage);
            }
            catch (Exception e)
            {
                options.OnError?.Invoke(createMessage, e);
                // If there's a Exception while generating the error page, re-throw the original exception.
            }
        }
Exemplo n.º 11
0
        protected static IElmahioAPI Api(string apiKey)
        {
            var api = ElmahioAPI.Create(apiKey, new ElmahIoOptions
            {
                Timeout   = new TimeSpan(0, 1, 0),
                UserAgent = new ProductInfoHeaderValue(new ProductHeaderValue("Elmah.Io.Cli", _assemblyVersion)).ToString(),
            });

            return(api);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Construct a sink that saves logs to the specified storage account.
        /// </summary>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="apiKey">An API key from the organization containing the log.</param>
        /// <param name="logId">The log ID as found on the elmah.io website.</param>
        public ElmahIoSink(IFormatProvider formatProvider, string apiKey, Guid logId)
        {
            _formatProvider = formatProvider;
            _logId          = logId;
            _client         = ElmahioAPI.Create(apiKey);
            var entryAssembly = Assembly.GetEntryAssembly();
            var assemblyName  = entryAssembly.GetName();

            _version = assemblyName.Version.ToString();
        }
Exemplo n.º 13
0
 private void EnsureClient()
 {
     if (Client == null)
     {
         var api = (ElmahioAPI)ElmahioAPI.Create(_apiKey);
         api.HttpClient.Timeout = new TimeSpan(0, 0, 5);
         api.HttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("Elmah.Io.Log4Net", _assemblyVersion)));
         Client = api;
     }
 }
Exemplo n.º 14
0
        public async void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnviroment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                try
                {
                    _logger.LogInformation(1, data.ToString(), "Log de Auditoria");
                }
                catch
                {
                }
            }

            if (_hostingEnviroment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "Eventos.IO",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };


                var client = ElmahioAPI.Create("0b8f6c34-6e07-4dae-8d6b-5f35f84e52a7");
                await client.Messages.CreateAsync(new Guid("ae189cd6-4491-49ae-8f38-bf49f5f36627").ToString(), message);
            }
        }
        // Estou registrando aqui erros de auditoria
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnviroment.IsDevelopment())
            {
                // Objeto anonimo com algumas informações determinadas
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    Url          = context.HttpContext.Request.GetDisplayUrl(),
                    TimeStamp    = DateTime.Now
                };

                // Estou fazendo o log de erro e deixando de usar o recurso de logo de erro, este log não vai para o Elmah pois está sendo tratado aqui
                // ssbcvp - Por questões de performance estou desabilitando o log
                // _logger.LogInformation(1, "Log de Auditoria", data.ToString());
            }

            // ssbcvp - voltar aqui - não consegui pegar o log de auditoria no swagger
            if (_hostingEnviroment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "Eventos.IO",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };

                // Fiz a autenticação no Elmah
                var client = ElmahioAPI.Create("ccde64921fbd4ef69bd01c1a097251af");
                client.Messages.Create(new Guid("809c3d10-450a-4395-bd4a-7fa23aaae94f").ToString(), message);
            }
        }
Exemplo n.º 16
0
        public async void OnActionExecuted(ActionExecutedContext context)
        {
            var config = new ConfigurationBuilder().SetBasePath(_hostingEnviroment.ContentRootPath).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddJsonFile($"appsettings.{_hostingEnviroment.EnvironmentName}.json", optional: true).Build();

            if (_hostingEnviroment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                _logger.LogInformation(1, data.ToString());
            }

            if (_hostingEnviroment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "Contas",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList()
                                      //Detail = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };

                var client = ElmahioAPI.Create(config.GetSection("ElmahConfiguration:ApiKey").Value);
                await client.Messages.CreateAndNotifyAsync(new Guid(config.GetSection("ElmahConfiguration:LogId").Value), message);
            }
        }
Exemplo n.º 17
0
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnviroment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                _logger.LogInformation(1, data.ToString(), "Log de Auditoria");
            }

            if (_hostingEnviroment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "Eventos.IO",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };


                var client = ElmahioAPI.Create("8f46c7cd9bfe4a618abf7a5ea652d0d9");
                client.Messages.Create(new Guid("19ad15fd-5158-4b7a-b36d-ab56dfe4500a").ToString(), message);
            }
        }
Exemplo n.º 18
0
        public async void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnviroment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                _logger.LogInformation(1, data.ToString());
            }

            if (_hostingEnviroment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "Eventos.IO",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };


                var client = ElmahioAPI.Create("e1ce5cbd905b42538c649f6e1d66351e");
                await client.Messages.CreateAndNotifyAsync(new Guid("adee8feb-4afb-4d2c-859d-30f729d47793"), message);
            }
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnviroment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                //_logger.LogInformation(1, Convert.ToString(data.ToString()), "Auditoria");
            }

            if (_hostingEnviroment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "SeuEvento",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };


                var client = ElmahioAPI.Create("12245a4a7e4444f388b4d5be34a149d6");
                client.Messages.Create(new Guid("7d9f3536-e431-46d1-954e-3aa39a74001c").ToString(), message);
            }
        }
        public async void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnviroment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                _logger.LogInformation(1, data.ToString());
            }

            if (_hostingEnviroment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "DiretivaTech",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };


                var client = ElmahioAPI.Create("db89eadb778d4de08a85296cb48b84e4");
                await client.Messages.CreateAndNotifyAsync(new Guid("5e299c42-e14a-4ebe-9d38-19f7cf650266"), message);
            }
        }
Exemplo n.º 21
0
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnviroment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                _logger.LogInformation(1, data.ToString());
            }

            if (_hostingEnviroment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "Extesao",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };


                var client = ElmahioAPI.Create("4a6c1791006e41ffa826a612096a8293");
                //await client.Messages.CreateAndNotifyAsync(new Guid("1669ed24-9c1e-47c5-b776-6588be61c064"), message);
            }
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnvironment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                _logger.LogInformation(1, data.ToString());
            }

            if (_hostingEnvironment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "duoSpeak",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dado a mais", DadoInfo = "Pode ser um Json" })
                };

                var client = ElmahioAPI.Create("aa9db5ab723a4d34a6cdfa1def53fd92");
                client.Messages.Create(new Guid("f212c380-9733-436a-942b-b34256d04a4d").ToString(), message);
            }
        }
Exemplo n.º 23
0
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnvironment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };

                _logger.LogInformation(1, data.ToString());
            }

            if (_hostingEnvironment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "Eventos.IO",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };
                var client = ElmahioAPI.Create("81378002d1044733af806b28394199d0");
                client.Messages.Create(new Guid("b7411135-9483-4675-945c-067f8544bf00").ToString(), message);
            }
        }
Exemplo n.º 24
0
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables().Build();

            var apiKey = config["ApiKey"];
            var logId  = new Guid(config["LogId"]);

            var client = ElmahioAPI.Create(apiKey);

            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseConfiguration(config)
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .ConfigureLogging(l => l.AddConsole(config.GetSection("Logging")))
                       .ConfigureServices(s => s.AddRouting())
                       .Configure(app =>
            {
                app.UseRouter(r =>
                              r.MapPost("reportOnly", async(request, response, routeData) =>
                {
                    using (var streamReader = new StreamReader(request.Body))
                    {
                        var body = streamReader.ReadToEnd();
                        await client.Messages.CreateAndNotifyAsync(
                            logId, new CreateMessage
                        {
                            Title    = "Content-Security-Policy report",
                            Severity = Severity.Information.ToString(),
                            Detail   = body,
                            Hostname = request.Headers["Referer"],
                        });
                    }
                }));
            })
                       .Build();

            host.Run();
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (_hostingEnvironment.IsDevelopment())
            {
                var data = new
                {
                    Version      = "v1.0",
                    User         = context.HttpContext.User.Identity.Name,
                    IP           = context.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Hostname     = context.HttpContext.Request.Host.ToString(),
                    AreaAccessed = context.HttpContext.Request.GetDisplayUrl(),
                    Action       = context.ActionDescriptor.DisplayName,
                    TimeStamp    = DateTime.Now
                };
                _logger.LogInformation(1, "Log de Auditoria :" + data.ToString());
            }

            if (_hostingEnvironment.IsProduction())
            {
                var message = new CreateMessage
                {
                    Version         = "v1.0",
                    Application     = "Gerstor.IO",
                    Source          = "GlobalActionLoggerFilter",
                    User            = context.HttpContext.User.Identity.Name,
                    Hostname        = context.HttpContext.Request.Host.Host,
                    Url             = context.HttpContext.Request.GetDisplayUrl(),
                    DateTime        = DateTime.Now,
                    Method          = context.HttpContext.Request.Method,
                    StatusCode      = context.HttpContext.Response.StatusCode,
                    Cookies         = context.HttpContext.Request?.Cookies?.Keys.Select(k => new Item(k, context.HttpContext.Request.Cookies[k])).ToList(),
                    Form            = Form(context.HttpContext),
                    ServerVariables = context.HttpContext.Request?.Headers?.Keys.Select(k => new Item(k, context.HttpContext.Request.Headers[k])).ToList(),
                    QueryString     = context.HttpContext.Request?.Query?.Keys.Select(k => new Item(k, context.HttpContext.Request.Query[k])).ToList(),
                    Data            = context.Exception?.ToDataList(),
                    Detail          = JsonConvert.SerializeObject(new { DadoExtra = "Dados a mais", DadoInfo = "Pode ser um Json" })
                };

                var client = ElmahioAPI.Create("67352fb2dbd047e488354d7d74a10a1b");
                client.Messages.Create(new Guid("2fabadd6-1d95-43a0-a584-eb8dcb324c36").ToString(), message);
            }
        }
Exemplo n.º 26
0
        public async Task PublishAsync(HealthReport report, CancellationToken cancellationToken)
        {
            try
            {
                if (api == null)
                {
                    api = (ElmahioAPI)ElmahioAPI.Create(options.ApiKey, new ElmahIoOptions());
                    // Override the default 5 seconds. Publishing health check results doesn't impact any HTTP request on the users website, why it is fine to wait.
                    api.HttpClient.Timeout = new TimeSpan(0, 0, 0, 30);
                    api.HttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("Elmah.Io.AspNetCore.HealthChecks", _assemblyVersion)));
                }

                var createHeartbeat = new CreateHeartbeat
                {
                    Result      = Result(report),
                    Reason      = Reason(report),
                    Application = options.Application,
                };

                if (options.OnFilter != null && options.OnFilter(createHeartbeat))
                {
                    return;
                }

                options.OnHeartbeat?.Invoke(createHeartbeat);

                try
                {
                    await api.Heartbeats.CreateAsync(options.HeartbeatId, options.LogId.ToString(), createHeartbeat);
                }
                catch (Exception inner)
                {
                    options.OnError?.Invoke(createHeartbeat, inner);
                    throw;
                }
            }
            catch (Exception e)
            {
                logger?.LogError(e, "Error during publishing health check status to elmah.io.");
                throw;
            }
        }
Exemplo n.º 27
0
        public Worker(
            IHostApplicationLifetime hostApplicationLifetime,
            IOptions <RagingBullConfig> rbOptions,
            IOptions <TDAmeritradeConfig> tdOptions,
            IOptions <OCRConfig> ocrOptions,
            IOptions <GeneralConfig> generalOptions,
            IOptions <OrderConfig> orderOptions,
            IOptions <ElmahConfig> elmahOptions)
        {
            _hostApplicationLifetime = hostApplicationLifetime;
            _ragingBullConfig        = rbOptions.Value;
            _tdAmeritradeConfig      = tdOptions.Value;
            _ocrConfig     = ocrOptions.Value;
            _generalConfig = generalOptions.Value;
            _orderConfig   = orderOptions.Value;
            _elmahConfig   = elmahOptions.Value;

            ElmahClient = ElmahioAPI.Create(_elmahConfig.ApiKey);
            TDClient tdClient = new TDClient(_tdAmeritradeConfig);

            MarketDataClient = tdClient;
            string            lottoxDbPath   = _generalConfig.DatabasePath + "/LottoX.db";
            string            symbolsDbPath  = _generalConfig.DatabasePath + "/Symbols.db";
            PortfolioDatabase lottoxDatabase = new LitePortfolioDatabase(lottoxDbPath, symbolsDbPath);

            LivePortfolioClient = new LottoXClient(_ragingBullConfig, _ocrConfig, lottoxDatabase, MarketDataClient);

            if (_generalConfig.UsePaperTrade)
            {
                Log.Information("PAPER TRADING");
                string            paperDbPath        = _generalConfig.DatabasePath + "/Paper.db";
                string            paperSymbolsDbPath = _generalConfig.DatabasePath + "/PaperSymbols.db";
                PortfolioDatabase paperDatabase      = new LitePortfolioDatabase(paperDbPath, paperSymbolsDbPath);
                BrokerClient = new PaperTradeBrokerClient(paperDatabase, MarketDataClient);
            }
            else
            {
                Log.Information("*****Trading with real account");
                BrokerClient = tdClient;
            }
            OrderManager = new OrderManager(BrokerClient, MarketDataClient, _orderConfig);
        }
Exemplo n.º 28
0
 /// <summary>
 /// Construct a sink that saves logs to the specified storage account.
 /// </summary>
 /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
 /// <param name="apiKey">An API key from the organization containing the log.</param>
 /// <param name="logId">The log ID as found on the elmah.io website.</param>
 public ElmahIoSink(IFormatProvider formatProvider, string apiKey, Guid logId)
 {
     _formatProvider = formatProvider;
     _logId          = logId;
     _client         = ElmahioAPI.Create(apiKey);
 }
Exemplo n.º 29
0
        /// <inheritdoc />
        protected override async Task EmitBatchAsync(IEnumerable <LogEvent> events)
        {
            if (events == null || !events.Any())
            {
                return;
            }

            var client = _client;

            if (_client == null)
            {
                var api = ElmahioAPI.Create(_options.ApiKey, new ElmahIoOptions
                {
                    Timeout   = new TimeSpan(0, 0, 30),
                    UserAgent = UserAgent(),
                });
                api.Messages.OnMessage += (sender, args) =>
                {
                    _options.OnMessage?.Invoke(args.Message);
                };
                api.Messages.OnMessageFail += (sender, args) =>
                {
                    _options.OnError?.Invoke(args.Message, args.Error);
                };
                client = api;
            }

            var messages = new List <CreateMessage>();

            foreach (var logEvent in events)
            {
                var message = new CreateMessage
                {
                    Title           = logEvent.RenderMessage(_options.FormatProvider),
                    TitleTemplate   = logEvent.MessageTemplate?.Text,
                    Severity        = LevelToSeverity(logEvent),
                    DateTime        = logEvent.Timestamp.DateTime.ToUniversalTime(),
                    Detail          = logEvent.Exception?.ToString(),
                    Data            = PropertiesToData(logEvent),
                    Type            = Type(logEvent),
                    Hostname        = Hostname(logEvent),
                    Application     = Application(logEvent),
                    User            = User(logEvent),
                    Source          = Source(logEvent),
                    Method          = Method(logEvent),
                    Version         = Version(logEvent),
                    Url             = Url(logEvent),
                    StatusCode      = StatusCode(logEvent),
                    CorrelationId   = CorrelationId(logEvent),
                    ServerVariables = ServerVariables(logEvent),
                    Cookies         = Cookies(logEvent),
                    Form            = Form(logEvent),
                    QueryString     = QueryString(logEvent),
                };

                if (_options.OnFilter != null && _options.OnFilter(message))
                {
                    continue;
                }

                messages.Add(message);
            }

            try
            {
                await client
                .Messages
                .CreateBulkAndNotifyAsync(_options.LogId, messages)
                .ConfigureAwait(false);
            }
            catch (Exception e)
            {
                Debugging.SelfLog.WriteLine("Caught exception while emitting to sink: {0}", e);
            }
        }
Exemplo n.º 30
0
 public ElmahIoTraceListener(string apiKey, Guid logId)
 {
     _client = ElmahioAPI.Create(apiKey);
     _logId  = logId;
 }