This project is licensed under the terms of the Apache license 2.0.
ELMAH for Net.Standard and Net.Core (3.1, 5, 6)
Add nuget package elmahcore
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
.
services.AddElmah(options => options.Path = "you_path_here")
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.
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
});
public IActionResult Test()
{
HttpContext.RaiseError(new InvalidOperationException("Test"));
...
}
Since version 2.0 ElmahCore support Microsoft.Extensions.Logging
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"
};
});
Since version 2.0.5 ElmahCore can log the request body.
Since version 2.0.6 ElmahCore can log the SQL request body.
Since version 2.0.6 ElmahCore can log method parameters.
using ElmahCore;
...
public void TestMethod(string p1, int p2)
{
// Logging method parameters
this.LogParams((nameof(p1), p1), (nameof(p2), p2));
...
}
You can replace UseDeveloperExceptionPage to UseElmahExceptionPage
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
app.UseElmahExceptionPage();
}
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.
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.
Since version 2.2.0 tou can use full-text search and multiple filter.
Full-text search work on analyzed text fields.
Filters are available through either the Add filter button.
Or you can use filter icon to the right of the error field.
Currently supports only Memory and XmlFile error logs.
elmahcore's People
Forkers
funky81 ssdevref jsearles jrsearles andashape fearnotdaniel ivantodorov91 inhumanellama yringler ccyandy marsen samaws1 reginoprado barryadwyer ppongsakorn elangeluz afastrunner ucsb danieldevelops tbertuzzi consultnjs omuleanu vondella bionstt jtone123 nasirkhan07 pranathadoddy luca7993 psuvorov breggles shahzadnetlink alllucky1996 reciko conficient angelchinchillo followynne vish1991 miroslavgrozdanovski fafa-nyakpo irac-ding rtdemiray gavinis tayfunuyar externalsourcefork unclestranger jafin arsenikstiger sajidkhanz stevenmoberg freerider75 jonno12345 deshion tystol rlgnak kudzaitsapo fosomo codingdk ggnaegi dks50217 mostafa-elmoghazi fabman08 zolaikhahammad funclun dillishrestha alexandresanscartier anhgeeky jeffersoil booksir abolfathi emmanuelrolon mustafaalkan64 raceprouk fredatgithub cuteribs nickmza syb990597617 mohammad-abbasi2559 strike2867 sohanahmedsn dorucioclea alexwong3434 urbrioche mizanulsiddiqui janus-toendering jkam1211 belav thompson-tomo pampas3 onminhthienelmahcore's Issues
Support semicolon in EmailOptions MailRecipient.
Hi,
Can you add support for semicolon in EmailOptions MailRecipient and MailCopyRecipient.
[email protected];[email protected]
Thanks
Add an async CheckPermissionAction delegate.
Hi,
Can you add an async version of ElmahOptions CheckPermissionAction?
I have to do authorizations checks in this method that call some async methods.
Thanks
Page links & stylesheet not found when there is url path
ElmahCore is working well for app when url is like this : http://localhost/elmah
But when there is a path like : http://localhost/my.api/elmah
All resources are 404 because the path is not included.
I changed every :
var basePageName = ElmahRoot;
to
var basePageName = Request.PathBase + ElmahRoot;
And it's working
Can you please add theses changes ?
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.
Cant understand how to filter error
Hi,
I just want my ElmahCoreMvc to stop logging 401 error, how can I do that?
Help :(
How do I modify CheckPermissionAction to use custom authentication.
I would like to use a custom access authentication for the url. Is there a way to do this? When the page is requested I would like to check database credentials for access.
Fixed
Configuring authentication for path
Thanks guys for some awesome work! Are we going to get a way to restrict access to the Elmah url? Thank you once again!
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)
"# caller: @C:\Sources\ElmahCore\ElmahCore\Internal$\CallerInfo.cs:10 ElmahCore.HttpException: NotFound"
Hi,
We have been receiving 404 Not Found error pointing to the path: "# caller: @C:\Sources\ElmahCore\ElmahCore\Internal$\CallerInfo.cs:10 ElmahCore.HttpException: NotFound". Please help us fix this issue.
Thanks
There should be a way to replace the values in the Form Elements
It should be possible to remove data from form elements before they are inserted into the database. This would prevent things such as passwords from being inserted into the database.
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:
"Elmah local exception"
After upgrading to .Net Core 3.0 (not sure if it is related), I am getting an annoying log entry when things are just fine.
Besides, there is no description on why the library it is catching an error.
My logs are getting polluted with this unnecessary entry.
https://github.com/ElmahCore/ElmahCore/blob/master/ElmahCore.Mvc/ErrorLogMiddleware.cs
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.CallSiteVisitor
2.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.CallSiteVisitor
2.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:
- Get the latest source from git
- Add app.UsePathBase("/test"); to beginning of ElmahCore.Demo->Startup->Configure
- run and visit http://localhost:5000/test/el/mah
- 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
browser not rendering elmah panel on remote host
its perfect on local pc when i enter '/elmah' address in browser
but on remote host the output is web source (html code as plain/text) and browser doesn't render the source
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.
Line 119 in 7319554
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
Upgrade ElmahCore.Mvc to netstandard2.0
Upgrade ElmahCore.Mvc to netstandard2.0 so it can be used in a full framework asp.net core app.
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>
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.)
Here's a screen shot of the value of prop
:
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.
Is there some way to define what schema is used in Postgresql?
Is there some way to define what schema is used in Postgresql?
If i look in the master branch it seems to be hardcoded could you please enable us to set the Schema name.
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");
});
Style Sheet problem
On my app, i have the next url: http://localhost:port/myapi/
My elmah path is: /see/logs
When i try to open i use http://localhost:port/myapi/see/logs, it works but i have an error with the style sheets, it includes two times /myapi...i mean it look like: /myapi/myapi/see/logs.
Could you add some property to configure that or what i can do?
I'm using asp.netcore 2.2 with angularjs
Originally posted by @npfernandeztheillet in #3 (comment)
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);
Support for full framework.
Hi,
Can you add support for Asp.Net Core with full .net framework to the nuget package.
Thanks
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.