GithubHelp home page GithubHelp logo

elmahcore's Introduction

This project is licensed under the terms of the Apache license 2.0.

Using ElmahCore

ELMAH for Net.Standard and Net.Core (3.1, 5, 6)

alt text

Add nuget package elmahcore

Simple usage

Startup.cs

1)	services.AddElmah() in ConfigureServices 
2)	app.UseElmah(); in Configure

app.UseElmah() must be after initializing other exception handling middleware, such as (UseExceptionHandler, UseDeveloperExceptionPage, etc.)

Default elmah path ~/elmah.

Change URL path

services.AddElmah(options => options.Path = "you_path_here")

Restrict access to the Elmah url

services.AddElmah(options =>
{
        options.OnPermissionCheck = context => context.User.Identity.IsAuthenticated;
});

Note: app.UseElmah(); needs to be after

app.UseAuthentication();
app.UseAuthorization();
app.UseElmah();

or the user will be redirected to the sign in screen even if he is authenticated.

Change Error Log type

You can create your own error log, which will store errors anywhere.

    class MyErrorLog: ErrorLog
    //implement ErrorLog

This ErrorLogs available in board:

  • MemoryErrorLog – store errors in memory (by default)
  • XmlFileErrorLog – store errors in XML files
  • SqlErrorLog - store errors in MS SQL (add reference to ElmahCore.Sql)
  • MysqlErrorLog - store errors in MySQL (add reference to ElmahCore.MySql)
  • PgsqlErrorLog - store errors in PostgreSQL (add reference to ElmahCore.Postgresql)
services.AddElmah<XmlFileErrorLog>(options =>
{
    options.LogPath = "~/log"; // OR options.LogPath = "с:\errors";
});
services.AddElmah<SqlErrorLog>(options =>
{
    options.ConnectionString = "connection_string";
    options.SqlServerDatabaseSchemaName = "Errors"; //Defaults to dbo if not set
    options.SqlServerDatabaseTableName = "ElmahError"; //Defaults to ELMAH_Error if not set
});

Raise exception

public IActionResult Test()
{
    HttpContext.RaiseError(new InvalidOperationException("Test"));
    ...
}

Microsoft.Extensions.Logging support

Since version 2.0 ElmahCore support Microsoft.Extensions.Logging alt text

Source Preview

Since version 2.0.1 ElmahCore support source preview. Just add paths to source files.

services.AddElmah(options =>
{
   options.SourcePaths = new []
   {
      @"D:\tmp\ElmahCore.DemoCore3",
      @"D:\tmp\ElmahCore.Mvc",
      @"D:\tmp\ElmahCore"
   };
});

Log the request body

Since version 2.0.5 ElmahCore can log the request body.

Logging SQL request body

Since version 2.0.6 ElmahCore can log the SQL request body. alt text

Logging method parameters

Since version 2.0.6 ElmahCore can log method parameters. alt text

using ElmahCore;
...

public void TestMethod(string p1, int p2)
{
    // Logging method parameters
    this.LogParams((nameof(p1), p1), (nameof(p2), p2));
    ...
}

Using UseElmahExceptionPage

You can replace UseDeveloperExceptionPage to UseElmahExceptionPage

if (env.IsDevelopment())
{
   //app.UseDeveloperExceptionPage();
   app.UseElmahExceptionPage();
}

Using Notifiers

You can create your own notifiers by implement IErrorNotifier or IErrorNotifierWithId interface and add notifier to Elmah options:

services.AddElmah<XmlFileErrorLog>(options =>
{
    options.Path = @"errors";
    options.LogPath = "~/logs";
    options.Notifiers.Add(new ErrorMailNotifier("Email",emailOptions));
});

Each notifier must have unique name.

Using Filters

You can use Elmah XML filter configuration in separate file, create and add custom filters:

services.AddElmah<XmlFileErrorLog>(options =>
{
    options.FiltersConfig = "elmah.xml";
    options.Filters.Add(new MyFilter());
})

Custom filter must implement IErrorFilter. XML filter config example:

<?xml version="1.0" encoding="utf-8" ?>
<elmah>
	<errorFilter>
		<notifiers>
			<notifier name="Email"/>
		</notifiers>
		<test>
			<and>
				<greater binding="HttpStatusCode" value="399" type="Int32" />
				<lesser  binding="HttpStatusCode" value="500" type="Int32" />
			</and> 
		</test>
	</errorFilter>
</elmah>

see more here

JavaScript filters not yet impemented :(

Add notifiers to errorFilter node if you do not want to send notifications Filtered errors will be logged, but will not be sent.

Search And Filters

Since version 2.2.0 tou can use full-text search and multiple filter.

Full-text search work on analyzed text fields.

alt text

Filters are available through either the Add filter button.

alt text

Or you can use filter icon to the right of the error field.

alt text

Currently supports only Memory and XmlFile error logs.

elmahcore's People

Contributors

aidan-chang avatar breggles avatar chrisw-cr avatar codingdk avatar conficient avatar cvilla38 avatar danieldevelops avatar elmahcore avatar followynne avatar fosomo avatar giansalex avatar inhumanellama avatar jafin avatar jtone123 avatar marsen avatar michaelrall avatar mike-eason avatar nathangreaves-xplor avatar omuleanu avatar reciko avatar rlgnak avatar sajidkhanz avatar smaglio81 avatar yyordanov 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  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  avatar  avatar  avatar  avatar  avatar  avatar

elmahcore's Issues

Chrome Wraps HTML with <html>

IE11 and Edge display /elmah correctly.

Chrome, however, renders the raw HTML source content into the browser. A look at the Developer Tools Elements shows Chrome nested the content inside <html><body><pre> tags.

Headers

Content-Security-Policy: default-src 'self'; ...
Server: Kestrel
X-Content-Type-Options: nosniff
X-Powered-By: ASP.NET
X-XSS-Protection: 1

Source

<html>
   <body>
      <pre>
         <!-- ELMAH HTML Content Is Here -->
         <!DOCTYPE html>
         <html>
         ...
      </pre>
   </body>
</html>

This may be due to a missing Content-Type: text/html; charset=utf-8 header. Is there a configuration option to supply this header?

Exception not logged when run application with Kestrel

When I setup asp.net core project under my local IIS, exceptions are logged by the elmahcore. But when I run project from command line (with Kestrel only) using dotnet run command no exceptions logged, although the HttpContext.RiseError() is working well.
If I understand correctly it is because when I run with command line the application is started under development environment. And it looks that problem is in the order of the initialization of the exception handling middleware.
If it is initialized in this way:

app.UseElmah();

if (env.IsDevelopment())
{
   app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

The exceptions are not logged by the elmahcore in development environment.
But If it is initialized:

if (env.IsDevelopment())
{
   app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseElmah();

The exceptions are logged always.

So, I'd mention about this peculiarity in the documentation.

Error on Application Startup: TargetParameterCountException: Parameter count mismatch.

.NET Core 3

services.AddElmah<SqlErrorLog>(options => { options.ConnectionString = "My connection string here"; });
app.UseElmah();

This works fine locally(Win 7, IIS), but failed on Win Serv 2016. My local has the SDK installed and the server has the runtime, not sure if that makes a difference or not.

System.Reflection.TargetParameterCountException: Parameter count mismatch.
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at Microsoft.Extensions.PlatformAbstractions.ApplicationEnvironment.GetEntryAssembly()
   at Microsoft.Extensions.PlatformAbstractions.ApplicationEnvironment..ctor()
   at Microsoft.Extensions.PlatformAbstractions.PlatformServices..ctor()
   at Microsoft.Extensions.PlatformAbstractions.PlatformServices..cctor()
TypeInitializationException: The type initializer for 'Microsoft.Extensions.PlatformAbstractions.PlatformServices' threw an exception.
Microsoft.Extensions.PlatformAbstractions.PlatformServices.get_Default()
ElmahCore.ErrorLog..ctor()
ElmahCore.Sql.SqlErrorLog..ctor(string connectionString)
ElmahCore.Sql.SqlErrorLog..ctor(IOptions<ElmahOptions> option)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite scopedCallSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite scopedCallSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService<T>(IServiceProvider provider)
ElmahCore.Mvc.BuilderHelper+<>c+<<UseElmah>b__0_0>d.MoveNext()
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

ElamahCore giving exception System.ArgumentNullException: 'Value cannot be null. Parameter name: path1'

Please Help. If i write this piece of code that you suggest yesterday, I could not hit my API (it is giving 500 Internal Server Error) and if i move app.UseElmah() at the end then it works fine but giving the exception.

app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseElmah(); //moved
app.UseHttpsRedirection();
app.UseMvc();

Now i'm only logging error to the files
services.AddElmah(options =>
{
options.LogPath = "~/logs";
});

Please see attached image:

Screenshot_30

Can't use XML logger

I'm finding that either the log path is ignored and the errors are in memory or else the website won't start at all.

how do you log exception manually ?

how do you log exceptions manually ?
like elmah for MVC below

try 
{
    some code 
}
catch(Exception ex)
{
    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}

Elmah + Kestrel + Apache - Ubuntu

Hi how are you? I hope you are well.

We have an small app that use Kestrel & Apache (proxy reverse) on Ubuntu. For some reason, locally works well but when We try to run on the server it doesn't work.

Question:

  • Do you test it in this scenario?

Startup.cs

  • ConfigureServices
    services.AddElmah(options =>
    {
    options.ConnectionString = Configuration["ConnectionString:Elmah"];
    options.Path = "/ver/los/errores";
    });
  • Configure:

Thanks.
N.

CSS file not loading Core 3.0

After upgrading my project to the release of Core 3.0 the css file no longer loads and just returns an empty page.

I was able to reproduce this on the demo project in the repo just by upgrading it to core 3.0. I had to comment out

     app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

to run the project.

EDIT:
setting o.ConfigureKestrel(options => options.AllowSynchronousIO = true);
fixes the issue, but i am guessing is not a good solution

Inconsistent property SendYsod in EmailOptions

Hi,

I happened to find while browsing, the SendYsod in EmailOptions is assigned to NoYsod internally:

ElmahCore\ElmahCore.Mvc\Notifiers\ErrorMailNotifier.cs:
_noYsod = options.SendYsod;

protected bool NoYsod
{
get { return _noYsod; }
}

I guess the meaning of the property is just reversed.

Best Regards
Wicky

SQL not working with .Net Core 3.0 : Value cannot be null. (Parameter 'connectionString')

Elmah is working properly with .net Core 3.0 until I activate SQL logging.
When I switch from "services.AddElmah(" to "services.AddElmah(" I receive the following error even after configuring the connection string

• System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
• at ElmahCore.Sql.SqlErrorLog..ctor(String connectionString)
• at ElmahCore.Sql.SqlErrorLog..ctor(IOptions1 option) • --- End of stack trace from previous location where exception was thrown --- • at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) • at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument) • at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) • at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.b__0(ServiceProviderEngineScope scope)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
• at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
• at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
• at ElmahCore.Mvc.BuilderHelper.<>c.<b__0_0>d.MoveNext()
• --- End of stack trace from previous location where exception was thrown ---
• at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
• at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Here's how I configured Elmah

In ConfigureServices
`var options = Configuration.GetSection("Elmah").Get();
EmailOptions emailOptions = new EmailOptions
{
SmtpServer = options.Host,
MailSender = options.From,
MailRecipient = options.To,
MailSubjectFormat = $"Elmah - {options.ApplicationName} {options.Environnement} - Error ({{1}}): {{0}}"
};

        services.AddElmah<SqlErrorLog>(options =>
        {
            options.ConnectionString = options.ConnectionString;
            options.ApplicationName = options.ApplicationName;
            options.Notifiers.Add(new ErrorMailNotifier("Email", emailOptions));
        });`

In Configure
app.UseElmah();

Workaround

Replace "services.AddElmah(" by "services.AddElmah("­. It disables SQL logging but the error is successfully sent by email.

ElmahCore v1.2.5

ElmahCore.Sql v1.2.5

No license listed

I would like to use this in our project but there isn't a license listed. I need that to get it by legal in our organization. The original uses an apache 2.0 license. Is this one the same?

Email Server Validation

Would you be able to provide more documentation on email notifier configuration? I am not receiving any emails and have no idea what properties are required and if there are any issues being logged.

Thanks,

stylesheet 404 when there is url path

Hi,

I found an issue about stylesheet, it seems related to issue #3 but not yet fixed.

To re-produce the issue:

  1. Get the latest source from git
  2. Add app.UsePathBase("/test"); to beginning of ElmahCore.Demo->Startup->Configure
  3. run and visit http://localhost:5000/test/el/mah
  4. you can see stylesheet lost with 404 error, the wrong url is https://localhost:5001/test/test/el/mah/stylesheet?h=...
    the correct one should be https://localhost:5001/test/el/mah/stylesheet?h=...

Best Regards
Wicky

Error when accessing Request.Form

I am running into an issue when logging some errors into Elmah. I tracked it down to the access to Request.Form which is throwing an InvalidOperationException inside of the Error constructor. This appears to happen when there is no body - for example with AJAX JSON requests. I believe the HasFormContentType property should be checked before accessing the Form property.

_form = CopyCollection(string.IsNullOrEmpty(request.ContentType) ? null : request.Form);

Securing the ELMAH axd file

Hi!

Would it be possible to secure the axd file from the middleware? In the asp.net version, the web.config was able to determine who was allowed or not (e.g., deny users="*"). Right now, anyone can access the file, logged in or not.

I would appreciate any insight on this matter.

Thank you!

Securing ~/elmah in ASP.NET Core (via CheckPermissionAction?)

How can I secure access to view the log (~/elmah) in ASP.NET Core?
I tried this code but the context.User object does not seem to be populated when this runs.

options.CheckPermissionAction = context =>
{
return context.User.Identity.IsAuthenticated;
};

Thanks,

Jonathan

How to user xml filter?

I'm trying to use an elmah.xml with some filters, but it throws an exception of null reference.

Startup:

services.AddElmah<XmlFileErrorLog>(options =>
{
      options.FiltersConfig = "elmah.xml";
});

Xml filter:

<?xml version="1.0" encoding="utf-8" ?>
<elmah>
  <errorFilter>
    <test>
      <or>
        <!-- Filter 400 errors -->
        <equal binding="HttpStatusCode" value="400" type="Int32" />
        <!-- Filter 404 errors -->
        <equal binding="HttpStatusCode" value="404" type="Int32" />
      </or>
    </test>
  </errorFilter>
</elmah>

Error:
image

If I remove the type XmlFileErrorLog, the filter does not work.

Should I set the log directory to use the xml filter? What directory should I save the elmah.xml?

Thanks.

AspNetCore 3.0 - NullReferenceException reading context.Items

In AspNetCore 3.0, a null reference exception can occur when creating the Error object. The exception occurs on https://github.com/ElmahCore/ElmahCore/blob/master/ElmahCore/Error.cs#L171 when LoadVariables function is called from https://github.com/ElmahCore/ElmahCore/blob/master/ElmahCore/Error.cs#L141.

LoadVariables(serverVariables, () => context.Items, "Items_");

The exception only occurs if the context.Items collection is empty (which is pretty rare).

The Error.cs code is using reflection to retrieve the properties of the context.Items collection and it seems that AspNetCore 3.0 changed some of the behavior of the underlying ItemsDictionary used by context.Items. In more detail ...

In AspNetCore 3.0 it seems like the Microsoft.AspNetCore.Http.ItemsDictionary object had a slight modification. Internally, the class has an _items member which holds all the Items. In AspNetCore 2.2, the internal _items member was initialized when the class was initialized. However, in AspNetCore 3.0, it looks like the _items member is left null until it's first use. If it never gets used, it can be null when Error.cs tries to read from it.

Here's some screenshots:

So, at line 171 the newly created en variable (Microsoft.AspNetCore.Http.ItemsDictionary) has an internal _items dictionary which is null. It looks like the property being inspected is Items, which I think is using the private _items value.

The actual en variable is not null, but when the .GetEnumerator() function is implicitly called in the foreach function, that's when the NullReferenceException occurs. (This is probably a Microsoft bug, since that doesn't seem like normal behavior from a .GetEnumerator() call.)

image

Here's a screen shot of the value of prop:

image

I'll throw together a quick pull request with a potential code fix.

Is there anyway to use the old allowRemoteAccess option.

I'm creating a ASP.NET core 2.2 application which uses this awesome library, my only problem is that I can't seem to find a way to restrict remote access like you could in the older none core version.

Previously it was: allowRemoteAccess="0"

I would like stop people using the URL http://MyWebSite/Elmah publicly (I would like the application to return a 404) but on the local hosting server I would like the emah error page to display normally.

Is this possible? (or do you know how I could configure this in the app or IIS).

Many Thanks James

exception enumerator causes insufficient information log

In some cases (e.g. when an included css is not found returning a 404 error) the function
private void LoadVariables(NameValueCollection serverVariables, Func<object> getObject, string prefix) in Error.cs throw an exception at the instruction foreach (var item in en) if en.Count == 0

This is very bad because this causes an incomplete filling on error info, including the information about the non found object that causes the error itself. It is hence impossible to identify the issue and to fix it.
I simply included this instruction in the try-catch changing the code from

if (value is IEnumerable en && !(en is string))
                {
	                foreach (var item in en)
                    {
                        try
                        {

to

                try
                {
                    if (value is IEnumerable en && !(en is string)) 
                    {
                        foreach (var item in en)
                        {

and the info are now filled with the source of the error.

NOTE: the exception generated by foreach (var item in en) is due to an implicit call to .GetEnumerator() that will throw NullReferenceException.
This is know to be a .NET core issue that is expected to be fix only in 5.0.0-preview1

Package need more detailed wiki

Great work.

Can you develop the Wiki/doc a little bit so this become more useful to many others. e.g. I can't get the path to view the UI for the errorlog.

How to use ElmahCore with Oracle Database

I have an ASP.NetCore 2.1 project in which I need to use ElmahCore and connect it to oracle database to store my logs in it.
Is there any possible way to do this?
would anyone shed light upon this matter?
Thanks

MySql Error Log option

My app supports MsSql, Postgres and MySql. Would be great if there was a MySql option.

Documentation

The package lacks some documentation, that makes it hard to use. For example, when adding the Elmah service, there is no clue about the meaning of the option fields.

Is it possible to add a summary tag to the public items? That would greatly help to use this library.

ElmahCore not honoring custom URL Path

Having the following settings in ConfigureServices method works fine (I can see Elmah UI at /elmah as expected):

services.AddElmah<SqlErrorLog>(options => {
    options.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
});

But when using a custom path as shown below, nothing is shown at /test/elmah:

services.AddElmah<SqlErrorLog>(options => {
    options.Path = "~/test/elmah";
    options.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
});

How to stop Mail triggering in Elmahcore when HttpStatusCode value is 401 UnAuthorized

Hi
I am using Elmahcore for logging exceptions in .net core web api 2.2 application.
In that i have done the settings for Mail Triggering in startup.cs file is
services.AddElmah(options =>
{

            options.Path = @"elmah";
            options.LogPath = "~/logs";               
            options.Notifiers.Add(new ErrorMailNotifier("Email", emailOptions));
        });

whenever i tried to hit the web api url i am getting the unauthorized exception through mail

i need to stop the mail triggering whenever there is UnAuthorized exception came

please kindly help me out how to resolve this issue using filters.

No errors are inserting

I've configured the project based on the read me and I'm using sql server error logging method but errors are not adding to the related database.

ElmahCore not creating xml log files

Please help. ElmahCore not creating xml log files. I tried the given code in documentation but not working. and i can't find any solution on internet and given project ElmahCore.Demo
I tried below code in ConfigureServices of Startup.cs
services.AddElmah(options =>
{
options.LogPath = "~/Helpers/log";

        });

log without context manually

In Elmah mvc version, you can log manually for example in projects without HttpContext.

I can't find a way to that.

Not working with Blazor application

I configured the Blazor app that comes with .NET CORE 3.0 in VS2019, but no log is generated :-(

Added in Counter.razor page:

@code {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
        throw new InvalidOperationException("Test");
     }
}

Exception not logged to Database/File

Used ElmahCore in my asp.net core 2.1 web api project but exception is not logged to DB or Path
Below is the code

public void ConfigureServices(IServiceCollection services)
{
services.AddElmah(options => options.Path = @"C:");
services.AddElmah(options => options.ConnectionString = ConnectionString);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
);
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
}

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseElmah();
        app.UseCors("CorsPolicy");
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();
        else
            app.UseHsts();

        app.UseHttpsRedirection();

        app.UseMvc();
    }

NLog support

I was wondering if this would support Nlog because I want to use that to send to the various places.

.Net Core 3.0 - ElmahExtensions.RiseError not logging

I am using ElmahExtensions.RiseError in my global error handler. Since .net Core 3.0 it's not working anymore. The call is made to RiseError, I do not get an exception, but nothing is logged and I don't receive the email. If I remove the Global exception handler and throw an exception, Elmah sends the email correctly.

public override void OnException(ExceptionContext context) { ... ElmahExtensions.RiseError(context.Exception); base.OnException(context); }

I also tested ElmahExtensions.RiseError directly in my controller and I have the same issue. Nothing is logged.

Change access of ErrorLogMiddleware class to public for testability

I would propose that some classes be public so so they are testable. I'm willing to make a PR for the change, but want to gauge how you feel about it.

For example, I'd like to check that my configured filter creates the filter class with the correct options:

var config = new ConfigurationBuilder()
    .AddJsonFile($"configs/{configName}.json", false, true)
    .Build();
var services = new new ServiceCollection().MyCustomExtension(config);
var provider = services.BuildServiceProvider();

var errorLogger = provider.GetService<ErrorLog>();
Assert.IsType<SqlErrorLog>(errorLogger);

/* Here's the problem
   ErrorLogMiddleware is an internal class, but it also contains any configured 
   Notifiers and Filters
*/
ErrorLogMiddleware middleware = provider.GetService<ErrorLogMiddleware>(); // Does not work since

// I'd like to be able to do this
var filters = middleware.Filters.Where(x => x.typeof(MyCustomFilterType));
var notifiers = middleware.Notifiers.Where(x => x.typeof(MyCustomNotifierType));
Assert.Equal(1, filters.Count);
Assert.Equal(3600, filters.First().ExampleTimeOutInSeconds);


Assert.Equal(1, notifiers.Count);

XmlFileErrorLog - ArgumentNullException: Value cannot be null. Parameter name: path1

Tried to add ElmahCore into my application.
Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddAuthentication(sharedOptions =>
                {
                    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
                })
                .AddWsFederation(options =>
                {
                    options.Wtrealm = Configuration["wsfed:realm"];
                    options.MetadataAddress = Configuration["wsfed:metadata"];
                })
                .AddCookie();

            services.AddMvc()
                    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "ManagementAPI", Version = "v1" });
                c.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}\\SwaggerDoc.xml", true);
            });

            services.AddElmah<XmlFileErrorLog>(options =>
            {
                options.LogPath = "~/log";
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseMvc();

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ManagementAPI v1");
            });

            app.UseElmah();
        }
    }

When I'm trying to open /elmah , getting

An unhandled exception occurred while processing the request.
ArgumentNullException: Value cannot be null.
Parameter name: path1

System.IO.Path.Combine(string path1, string path2)

    ArgumentNullException: Value cannot be null. Parameter name: path1
        System.IO.Path.Combine(string path1, string path2)
        ElmahCore.XmlFileErrorLog..ctor(IOptions<ElmahOptions> options, IHostingEnvironment hostingEnvironment)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(IServiceCallSite callSite, TArgument argument)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(IServiceCallSite callSite, TArgument argument)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(IServiceCallSite callSite, TArgument argument)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(IServiceCallSite callSite, TArgument argument)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
        Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
        Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService<T>(IServiceProvider provider)
        ElmahCore.Mvc.BuilderHelper+<>c+<<UseElmah>b__0_0>d.MoveNext()
        Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
        Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
        Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
        Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
        Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
        Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
        Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Under debugger it throws System.ArgumentNullException: Value cannot be null. Parameter name: path1 at System.IO.Path.Combine(String path1, String path2) .

I'm hoping it's just wrong with my hands and not a bug.

P.S> Application runs on IIS, maybe that's a reason.

ELMAG_Error Rename Table

Is it posibble to rename rename table to something like ElmahError. If it is not this is a feature request. Thank you

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.