GithubHelp home page GithubHelp logo

roushtech / rollbardotnet Goto Github PK

View Code? Open in Web Editor NEW
7.0 4.0 5.0 195 KB

Home Page: https://www.nuget.org/packages/RollbarDotNet/

License: MIT License

C# 100.00%
rollbar dependency-injection dotnet dotnet-core

rollbardotnet's Introduction

RollbarDotNet

NuGet

Build Maintainability

Rollbar support for your .NET Core projects, relies on dependency injection and hooks up to your ASP.NET Core pipeline for easy use.

Inspired by RollbarSharp, great library, just required too many tweaks to make play with .NET core well in my opinion.

Testing

Environment variables for testing:

  • ROLLBAR_TOKEN - Rollbar token for testing.

Required services

Please make sure the following services are available for the various builder modules.

app.UseRollbarExceptionHandler();

Using in ASP.NET Core

Place the following after your error handling code in Startup.Configure:

app.UseRollbarExceptionHandler();

Place the following in your Startup.ConfigureServices section:

services.AddRollbarWeb(Configuration);

There is also one that doesn't load the builders for building out environment information for web servers (this will not attempt to crawl for server/client/request information):

services.AddRollbar(Configuration);

Hook up the rollar configuration using the following code:

services.AddOptions(); // Most apps already are using this, but just in case.
services.Configure<RollbarOptions>(options => Configuration.GetSection("Rollbar").Bind(options));

Configure Rollbar from your appSettings.json file like so:

  "Rollbar": {
    "AccessToken": "[access token here]",
    "Environment": "[named environment here]"
  }

Getting Occurrence UUIDs

Getting the occurrence UUID is easy, just get it from the HttpContext Feature collection:

public IActionResult Error()
{
    var response = HttpContext.Features.Get<IRollbarResponseFeature>();
    return Content(response.Uuid);
}

The UUID can be looked up directly via https://rollbar.com/occurrence/uuid/?uuid=[UUID HERE]. This may be really useful if you want to let your users report errors to you, you can include this UUID automatically in the report.

You can check if Rollbar has reported the exception via the IRollbarResponseFeature.Handled boolean.

Calling Directly

You can also post messages/exceptions directly if you so wish.

// Send an exception
var response = await this.Rollbar.SendException(exception);
response.Uuid //Event UUID that can be looked up on the rollbar site.


// Send a message
var response = await this.Rollbar.SendMessage("Hello World!", RollbarLevels.Message);

Calling Without Dependency Injection

Although I highly recommend using depdency injection, you can fairly easily configure Rollbar by hand:

var rollbarOptions = Options.Create(new RollbarOptions
{
    AccessToken = "token here",
    Environment = "development"
});
var rollbar = new Rollbar(
    new IBuilder[] {
        new ConfigurationBuilder(rollbarOptions),
        new EnvironmentBuilder(new SystemDateTime()), // SystemDateTime abstracts DateTime for mocking
        new NotifierBuilder()
    },
    new IExceptionBuilder[] {
        new ExceptionBuilder()
    },
    new RollBarClient(rollbarOptions)
);

try
{
    throw new Exception("Testing");
}
catch(Exception exception)
{
    await rollbar.SendException(exception); //Err... everything is async, keep that in mind.
}

Blacklists

Blacklisting will replace variables with asterisks ("**********") when data is sent to Rollbar.

Inside of your appSettings.json you have two options, using plaintext or regular expressions:

  "Rollbar": {
    "AccessToken": "[access token here]",
    "Environment": "[named environment here]",
    "Blacklist": {
      "Regex": [
        "^CreditCard.*$"
      ],
      "Text": [
        "Password"
      ]
    }
  }

Additional Blacklists can be coded by inheriting from the RollbarDotNet.Blacklisters.IBlacklister interface and registering it with your application's dependency injection framework.

To do

Implement stack frames

As of writing this .NET Core does not support walking the stack frames of the exception, means our error messages are pretty weak.

Log4net support

As far as I know log4net is currently implementing .NET Core support.

Break out into separate libraries

.NET Core is all about keeping things slim, do we put ASPNETCore code in a different lib?

.NET 4.5.1 support

Would be nice for this to support .NET 4.5.1, no testing and no real effort outside of some basic preprocessor stuff in place.

rollbardotnet's People

Contributors

mkdabrowski avatar patriotbob avatar strangewill avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

rollbardotnet's Issues

Somewhat iffy integration tests

While they're generally sufficient, we're actually bounding a 401 off of Rollbar on auth. We're just testing that DI has wired up and we haven't screwed up setting stuff up...

A more robust testing procedure would be best.

Update Docs

Docs don't have instructions on:

  • Disabled flag
  • How to use ILogger.

Dynamic Method Test

0.6.4 patched handling dynamic methods and some odd behaviors of them...

But ideally we'd like a test to cover them. I know how to make really basic dynamic methods using opcode, but I don't know how to take an method that throws an exception and convert that to a dynamic method yet (and I don't have a lot of time to figure that out right now).

#63

Returning The UUID Up Middleware Stack

When we send a message to Rollbar, we'll get the UUID of the message back, it would be nice to make that available to other middleware so that they can use it (eg: "here is a reference ID if you wish to contact us about this error").

So far I can think of a few options:

  • Wrap old exception with new custom exception and rethrow, containing the UUID as part of the exception information.
  • Populate a scoped injected class with the information which other middleware can also pull from.

Break Cookies Out

Cookies are sent as a block on the request section, when they can have their own section.

.NET Standard 2.0 Support

The new NETStandard adds much needed functionality for tracing....

So what do we do, do we support both NetStandard 2.0 and 1.0, with 1.0 being a reduced functionality set, or do we only support 2.0?

I'll have to start working on NetStandard 2.0 and get this lib on 1.0 soon anyway.

Sign the lib

A few discussions about malicious packages making into NPM has made me think heavily about what I can do to protect against someone trying to push a bad package to NPM.

Signing the lib and signatures of the nuget package may be the best option...

SendException and SendMessage fails for content type: application/json

Exception Message: "Incorrect Content-Type: application/json; charset=UTF-8"
StackTrace

   at Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()
   at RollbarDotNet.Builder.RequestBuilder.BuildRequest(Request request)
   at RollbarDotNet.Builder.RequestBuilder.Execute(Payload payload)
   at RollbarDotNet.Rollbar.ExecuteBuilders(Payload payload)
   at RollbarDotNet.Rollbar.SetupPayload(RollbarLevel level)
   at RollbarDotNet.Rollbar.<SendException>d__14.MoveNext()

This could be because I am calling SendException from custom middleware.

Thanks.

Possibly Stop Using IHttpContextAccessor

As part of this announcement: aspnet/Hosting#793 which caused error #32, the .NET Core team said they removed IHttpContextAccessor because of "non-trivial performance costs".

Is there another option for adding Features to HTTPContext that is better performance wise?

throws exceptions. does not work

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeLoadException: Could not load type 'Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions' from assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
at RollbarDotNet.Core.ServiceExtensions.AddRollbarWeb(IServiceCollection services, IConfigurationRoot configuration)
at Uqualio.Startup.ConfigureServices(IServiceCollection services)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection exportServices)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Uqualio.Program.Main(String[] args)

Error Adding Rollbar -- Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'

Hi,

I am trying to use your rollbar intergration in my dotnet CORE WebApi. But when I add the required lines of code (reading of your README) I get the following error

Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'RollbarDotNet.Builder.RequestBuilder

I've tried to add the lines of different places in my startup class, but still getting the errors. Any idea of what I am doing wrong?

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRollbarWeb(Configuration);
            services.AddSingleton(Configuration);

            services.AddElm(options =>
            {
                options.Path = new PathString("/elm");
                options.Filter = (name, level) => level >= LogLevel.Error;
            });

            services.AddMvc();

            services.AddOptions();

            services.Configure<ApiSettings>(Configuration.GetSection("ApiSettings"));

            // Configure mappings
            Mappings.ConfigureMappings();
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseRollbarExceptionHandler();

            app.UseCors(builder =>
               builder.WithOrigins("http://localhost:9000")
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .AllowCredentials()
               );

            app.UseElmPage();
            app.UseElmCapture();
            app.UseMvc();
        }

Add IHttpContextAccessor To Service List, Add Service Tests

All coming out of #33, basically Identity registers IHttpContextAccessor, and in #32 we found to just register the service manually to get around that when not using Identity.

However, I'd like to not make that manual, so few things:

  1. We missed this due to our lack of testing our DI settings, we should get some basic DI in our tests rolling so we can test bare implementations (and possibly add tests for conflicts we may run into).
  2. We want to go ahead and configure this, so lets take a look at how .NET's Identity framework does it, make sure we won't have any conflicts, detail the changes in the docs.

Inner Exception Support?

Got this while working on another project:

CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information.

I need to automatically unpack inner exceptions. Doh.

NullReferenceException

When trying to call Rollbar.SendMessage, I'm getting a NullReferenceException. Using Rollbar.SendException works fine. I think it may be due to Body.Message not being initialized, then payload.Data.Body.Message.Body = message is called. I noticed that a new Body is initialized in the Data constructor, but no Message is initialized in the Body constructor.

For what it's worth, I've been trying to use this in a custom ILogger. I was thinking that I might have configured something wrong, but I noticed that missing initialization so I thought I'd bring it up.

Thanks!

What Should 1.0.0 Contain?

Trying to run with solid Semver here...

  • Separate libraries for core Rollbar and Rollbar support for web apps, minimum requirements for the former. The idea of a "core" Rollbar set would be to be able to run console apps and whatnot (see #29) without any requirements on ASP.Net Core components.
  • Align near a netstandard2.0 release date? I can't really support Rollbar to the level that I'd like until that comes out. (#1) I feel it is silly to come out with a "1.0" release when I'm missing frame support (though we'll probably still build a netstandard1.0 version without frame support).
  • .NET Core best practices (already moving to IOptions<> and a few other tweaks here and there).

Ideally we'll want to run up to this with the various 0.x.y releases, if at all possible we'll want to keep our main interfaces with the libraries the same (eg: most auto-configuration through extensions should continue to work fine with the split of the core/web libraries, and just swapping out the libs and recompiling should work fine). However breaking changes will probably happen (such as moving from IConfigurationRoot to IOptions<> already planned for 0.5.0).

I'm going to keep this open running up to netstandard2.0's release in an attempt to let everyone chuck in their ideas on this.

Tie Into ILogger

Make it so we can consume it through ASP.NET Core's logging, we'll also want to set a threshold for it.

If the logger errors, it'll throw upwards

Hmm, probably should have an option so that if a logger fails we don't explode in your face.

Typically happens when you're being limited (gone over your total allotted amount of calls) but still...

API error: Invalid format. data.body.message.body is missing and it is required.

When calling SendException() in my middleware:

var response = await _rollbar.SendException(ex);

I get the following exception:

{
  Connection: keep-alive
  Date: Fri, 10 Mar 2017 09:44:05 GMT
  Server: nginx
  Access-Control-Allow-Origin: *
  Access-Control-Allow-Credentials: true
  X-Response-Time: 6ms
  Content-Length: 100
  Content-Type: application/json; charset=utf-8
}

The associated error in rollbar is:

API error: Invalid format. data.body.message.body is missing and it is required.

As far as I can tell my configuration looks okay, the Rollbar class appears to be properly instantiated with 6 builders and a single exception builder. I get the same error if i use services.AddRollbar(), services.AddRollbarWeb() or use your own middleware class: app.UseRollbarExceptionHandler();

SendMessage function works as expected.

Add Filtering

Should be able to filter exceptions that are reported. Will only apply to ASP.NET Core Filtering

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.