GithubHelp home page GithubHelp logo

mroach / rollbarsharp Goto Github PK

View Code? Open in Web Editor NEW
53.0 13.0 42.0 159 KB

.NET bindings for the Rollbar.com error reporting service.

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

License: Apache License 2.0

C# 99.87% ASP 0.13%

rollbarsharp's Introduction

NOTE: No longer in active development

The Rollbar team has done an excellent job creating an official .NET client over at https://github.com/rollbar/Rollbar.NET. It's recommened to use this for new projects and to migrate existing projects to the client. This project is no longer maintained. Thanks to everyone who contributed over the life of this project.

RollbarSharp

Build status NuGet version Nuget downloads Coverage Status

.NET bindings for Rollbar.

I'm not affiliated with Rollbar, I just like their service.

Minimum version is .NET 4.5. There's also a dependency on System.Web.Routing, so you'll at least need ASP.NET MVC installed on the system.

Installation

RollbarSharp is available on Nuget and can be installed by:

PM> Install-Package RollbarSharp

Usage

Configuration

The easiest way to get going is to add the Rollbar.AccessToken item to your app settings.

<configuration>
  <appSettings>
    <add key="Rollbar.AccessToken" value="YOUR_TOKEN_HERE"/>
    <add key="Rollbar.Environment" value="production"/>
  </appSettings>
</configuration>

From there, you have several options on how to integrate with your app.

As an ASP.NET Filter

public class RollbarExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled)
            return;

        (new RollbarClient()).SendException(filterContext.Exception);
    }
}

And then in Global.asax.cs you can do

GlobalFilters.Filters.Add(new RollbarExceptionFilter());

Or if you're using an inversion of control system that supports binding filters, you could do it there. This is an example with Ninject. You could even dependency-inject the RollbarClient if you want to create it in your own factory method.

kernel.BindFilter<RollbarExceptionFilter>(FilterScope.Global, 10).InSingletonScope();

The OnException method could instead be used verbatim inside a Controller if you add the override keyword. protected override void OnException(ExceptionContext filterContext) ...

As an ASP.NET application event handler (Global.asax.cs)

protected void Application_Error(object sender, EventArgs e)
{
    var exception = Server.GetLastError().GetBaseException();

    (new RollbarClient()).SendException(exception);
}

As an HttpModule in the Web.config

IIS Integrated Pipeline

<system.webServer>
    <modules>
        <add name="RollbarHttpModule" type="RollbarSharp.RollbarHttpModule"/>
    </modules>
</system.webServer>

IIS Classic Pipeline

<system.web>
    <httpModules>
        <add name="RollbarHttpModule" type="RollbarSharp.RollbarHttpModule"/>
    </httpModules>
</system.web>

As an NLog target

You'll need to add the NLog.RollbarSharp assembly to your project for this to work but it's available on NuGet. Check out the NLog.RollbarSharp README for configuration details, but here's the skinny:

<nlog>
    <extensions>
        <add assembly="NLog.RollbarSharp" />
    </extensions>
    <targets>
        <target xsi:type="RollbarSharp" name="rollbar" />
    </targets>
    <rules>
        <logger name="*" minlevel="Warn" writeTo="rollbar" />
    </rules>
</nlog>
<appSettings>
    <add key="Rollbar.AccessToken" value="6703358e9f54081e59bb0d65ee066363"/>
    <add key="Rollbar.Environment" value="development"/>
</appSettings>

Bugs

  • If you encounter a bug, performance issue, or malfunction, please add an Issue with steps on how to reproduce the problem.

Building

I'm using ScriptCs for managing the build process.

To build go to build folder and then run this command:

scriptcs -script build.csx

After that, upload new RollbarSharp.{version}.nupkg to nuget.

TODO

  • Add more tests

rollbarsharp's People

Contributors

albertomonteiro avatar atrejoe avatar bgurmendi avatar mm-pkohlhoff avatar mroach avatar mzochowski avatar richardversluis avatar sierzput avatar uvcrew avatar webcoyote avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rollbarsharp's Issues

This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked.

This error occurs when trying to log an exception that took place inside a WCF Rest Service.

Excerpt from Stacktrace:
at System.Web.HttpRequest.EnsureFiles()
at System.Web.HttpRequest.get_Files()
at RollbarSharp.Builders.RequestModelBuilder.CreateFromHttpRequest(HttpRequest request, HttpSessionState session, String[] scrubParams)
at RollbarSharp.Builders.RequestModelBuilder.CreateFromCurrentRequest(String[] scrubParams)
at RollbarSharp.Builders.DataModelBuilder.Create(String level, BodyModel body)
at RollbarSharp.Builders.DataModelBuilder.CreateExceptionNotice(Exception ex, String message, String level)
at RollbarSharp.RollbarClient.SendException(Exception ex, String title, String level, Action1 modelAction) at RollbarSharp.RollbarClient.SendErrorException(Exception ex, String title, Action1 modelAction)

Missing Gemfile with accurate version restrictions

There's no Gemfile, and the Rake file doesn't work against the latest version of Albacore. I tried adding a Gemspec limiting to v1 but evidently it didn't work against the latest version of v1 either...

Can anyone share what versions of these packages they're actually using to build this? I'm looking to get a NuGet package out rather than just Build from Visual Studio. Thanks!

Issue when posting HTML even though [AllowHtml] attribute set

Hi,

Great tool ... really want to get cracking using it, but have come across an issue:

If the [AllowHtml] attribute is set on a field, and HTML content is posted and an exception is subsequently raised, RollbarSharp ignores the actual exception but shows the standard error you would get as if [AllowHtml] was not set.

Json exceptions from rollbarsharp

Some exceptions are causing rollbarsharp exceptions.

Have you seen this ->

Application: w3wp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(Newtonsoft.Json.JsonReader, Newtonsoft.Json.Serialization.JsonContract, Boolean)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(Newtonsoft.Json.JsonReader, System.Type, Boolean)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(Newtonsoft.Json.JsonReader, System.Type)
at Newtonsoft.Json.JsonConvert.DeserializeObject(System.String, System.Type, Newtonsoft.Json.JsonSerializerSettings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.String, Newtonsoft.Json.JsonSerializerSettings)
at RollbarSharp.Result.TryParseResponse(System.String)
at RollbarSharp.RollbarClient.HttpPostAsync(System.String, System.Object)
at System.Threading.Tasks.Task.Execute()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef)
at System.Threading.Tasks.Task.ExecuteEntry(Boolean)
at System.Threading.ThreadPoolWorkQueue.Dispatch()

Another error -

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at RollbarSharp.Result.TryParseResponse(String response)
at RollbarSharp.RollbarClient.HttpPostAsync(String payload, Object userParam)
at System.Threading.Tasks.Task.Execute()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
at System.Threading.Tasks.Task.ExecuteEntry(Boolean bPreventDoubleExecution)
at System.Threading.ThreadPoolWorkQueue.Dispatch()

It is possible to use with desktop app?

I would like to use with desktop application for example created with WPF.
It is possible? Because I can see some ASP.NET MVC dependencies?

Regards,
Tomasz Kowalczyk

.NET Core Support?

Any plans for getting this to support .NET Core? I've already started the process but don't want to run too far down this rabbit hole if someone has already done it/mostly completed it.

Sending person details along with error functionality not available

I wanted to send additional information to Rollbar about the user that encountered the error. At the moment, this functionality is not available in this package.
I did however notice that @travisrussi has implemented this functionality in a fork of this package; https://github.com/travisrussi/RollbarSharp
Could this functionality be implemented in the core package?
Perhaps @travisrussi could submit a pull request of his version.

PersonModel for non-web usage

I would be cool if it would be possible to specify the PersonModel when logging exceptions.

I took a glance at the code, and the PersonModel is only populated when HttpContext.Current exists and is then populated from AUTH_USER,LOGON_USER or REMOTE_USER server variables respectively.

Another option is to populate the Person model from the environment..... You know what, I'll submit a pull request for that!

Issue with User IP and X-Forwarded-By

Not sure how to fix this but this method.

private static string IpFromXForwardedFor(HttpRequest request)
{
    var forwardedFor = request.Headers["X-Forwarded-For"];
    if (!string.IsNullOrEmpty(forwardedFor) && forwardedFor.Contains(","))
    {
        forwardedFor = forwardedFor.Split(',').Last().Trim();
    }
    return forwardedFor;
}

Didn't work well with my setup with Cloudflare. My header was like this.

X_FORWARDED_FOR: 196.215.208.37, 197.214.212.59:57956

Where the first one is the "good ip" and the second one is from Cloudflare. RollbarSharp was taking the last one and Rollbar didn't even accept that as an IP (because of the port i guess) and well it's the Cloudflare IP anyway so not that interesting. Just wanted to let you know. I run with a fork now where i take the first IP instead.

Release of user params?

Any chance you can make a nuget release to get the userParams out?

Thank you for this simple and clean project.

Can't log "context"

It seems silly at first glance to be doing this from the server, but we are trying to link server request failures to client errors using this context field (so it is searchable).

client.SendException(aFilterContext.Exception, null, null, n => { n.Context = "..."; });

Can you add this to the Serialization.DataModel?

Send server.root to integrate with GitHub

Per https://rollbar.com/docs/github/ and https://rollbar.com/docs/just-your-code/

Rollbar is better with GitHub! [...] link your Rollbar stack traces to the code where it happened, resolve items when a particular commit is deployed, and show the commits that were included with each deploy.

In order to let our servers know that you want it to try linking your stack trace to the files on GitHub you should send the "server.root" key. A lot of the time that can be "/", to indicate that all files can be linked to a file in GitHub.

All official Rollbar notifiers can send this key. See the documentation for your notifiers to learn exactly how.

Update docs for ASP.NET 5 / vNext support

As you may know, the exception filter stuff doesn't work the same in ASP.NET vNext as far as I can tell. The following steps work there instead. Consider updating the docs or adding a separate readme?

Create an ILogger:

public class RollbarExceptionLogger : ILogger
{
    public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
    {
        if (exception == null)
            return;

        const string accessToken = "YOUR_SERVER_ACCESS_TOKEN";
        RollbarClient rollbar = new RollbarClient(accessToken);
        rollbar.SendException(exception);
    }

    public bool IsEnabled(LogLevel logLevel)
    {
#if DEBUG
        return false;
#else
        return true;
#endif
    }

    public IDisposable BeginScopeImpl(object state)
    {
        return null;
    }
}

Next create a ILoggerProvider to generate them upon request.

public class RollbarExceptionLoggerProvider : ILoggerProvider
{
    public void Dispose()
    {
    }

    public ILogger CreateLogger(string categoryName)
    {
        return new RollbarExceptionLogger();
    }
}

Finally, install it in your Startup.cs's configure method call:

public class Startup
{
            public void Configure(IApplicationBuilder app, IHostingEnvironment env,
        ILoggerFactory loggerFactory, IOptions<MvcJsonOptions> mvcOptions )
    {
        Environment = env;
        mvcOptions.Value.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddProvider(new RollbarExceptionLoggerProvider());
        loggerFactory.AddDebug();
                   // ...
           }
    }

IExceptionFilter members different from documentation

According to the documentation:

public class RollbarExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled)
            return;

        (new RollbarClient()).SendException(filterContext.Exception);
    }
}

However, IExceptionFilter requires the following methods:

public bool AllowMultiple { get; }

public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
    throw new System.NotImplementedException();
}

Please update the documentation.

Catch (exeption)

Hi with the following code it doesnt post the exception..
catch (Exception ex2)
{
var d = new RollbarClient().SendErrorException(ex2);
}

the variable d comes back with a id and running fine with other functions.

Can't set title or error level when using SendException

Hello. Nice work here... I just can't figure out why title is not being set when I send an exception like so:

client.SendException(ex, "My own message"); // Still shows exception message as title
client.SendException(ex, null, "warning"); // Shows as level "error"

I also tried using the action model with no luck.

client.SendException(ex, null, null, n =>{ n.Title = "My own message" });

BTW, the action model works for me when I use it to send Custom data. Very nice!

Any ideas?

Can't log exceptions when Request.Form contains XML

// Send exception to Rollbar
var client = new RollbarClient(lRollbarConfig);

client.SendException(aFilterContext.Exception, null, null, 
n => { n.Person.Username = remoteLogData.UsernameWithLoadId;
          n.Person.Id = remoteLogData.UsernameWithLoadId;

Getting the popular A potentially dangerous Request.Form value was detected from the client error because aFilterContext.HttpContext.Request.Form contains some XML, This is a huge buzz kill because almost all of our requests have XML in them, so we aren't seeing any of our server errors.

Any idea how we can get around this? Is my only option to html encode the Request.Form XML values on the client before they are even sent? We use MVC so we get around this in our requests by using ValidateInput(false) as seen here but you can see there are other solutions such as setting the request validation mode to 2.0.

A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property.

Hi Michael,

I'm currently trying to pinpoint down a problem possibly with RollbarSharp. My application pool crashed and this was the error found in the Event Viewer. Could it be that there goes something wrong with the task that sends the exception async?

An unhandled exception occurred and the process was terminated.

Exception: System.AggregateException

Message: A Task's exception(s) were not observed either by Waiting on the Task or     accessing its Exception property. As a result, the unobserved exception was rethrown     by the finalizer thread.

StackTrace:    at System.Threading.Tasks.TaskExceptionHolder.Finalize()

InnerException: System.NullReferenceException

Message: Object reference not set to an instance of an object.

StackTrace:    at RollbarSharp.RollbarClient.OnRequestCompleted(WebResponse response)
   at RollbarSharp.RollbarClient.HttpPostAsync(String payload)
   at System.Threading.Tasks.Task.Execute()

Threadsafety

Safe to assume that a new RollbarClient is entirely threadsafe? you can put an instance in a static class field and reuse it from any number of threads?

Error when trying to log from Application_Start()

I log when my application starts up and I'm getting an error when using RollbarSharp to do this. I think that the problem is RollbarSharp.Builders.RequestModelBuilder.CreateFromCurrentRequest(String[] scrubParams) method tries to access HttpContext.Current and according to http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart/ the HttpContext is not available in the Application_Start() method.

This is causing the error "Request is not available in this context" to be thrown when the application is starting up.

Filter/Scrub properties from POST request

Hi,
How do I go about defining properties to scrub from a POST request?
I'm currently sending errors with

(new RollbarClient()).SendException(exception);

Thanks for the help.

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.