Git Product home page Git Product logo

microsoft.extensions.logging.log4net.aspnetcore's People

Contributors

bdovaz avatar diomedesdominguez avatar huorswords avatar justusgreiberorgadata avatar rholek-idg avatar twenzel avatar willwolfram18 avatar wilsonpan 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

microsoft.extensions.logging.log4net.aspnetcore's Issues

loggerFactory.AddLog4Net() not finding log4net.config when hosting the app in a Windows Service

Hello,

I implemented the code described here:
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-2.1

The problem is that the app is crashing when starting the service...

When looking at Event Viewer, it shows that log4net.config is not being searched at the right location as configured per the URL linked above.

var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);

pathToContentRoot is correctly pointing to the folder where the .exe file is placed and I can see that log4net.config is also present in this directory. However, the runtime is looking for the log4net.config file at C:\WINDOWS\system32\log4net.config.

Do you have any idea why this is happening?
Is there a way to hardcode the path to log4net.config?

This is the exception in Event Viewer:

Log Name:      Application
Source:        .NET Runtime
Date:          8/5/2018 3:52:47 AM
Event ID:      1026
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      LenielMaccaferri
Description:
Application: FileGetter.exe
CoreCLR Version: 4.6.26628.5
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException: Could not find file 'C:\WINDOWS\system32\log4net.config'.
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.OpenRead(String path)
   at Microsoft.Extensions.Logging.Log4NetProvider.ParseLog4NetConfigFile(String filename)
   at Microsoft.Extensions.Logging.Log4NetProvider..ctor(String log4NetConfigFile, Boolean watch, IConfigurationSection configurationSection)
   at Microsoft.Extensions.Logging.Log4NetProvider..ctor(String log4NetConfigFile, Boolean watch)
   at Microsoft.Extensions.Logging.Log4NetExtensions.AddLog4Net(ILoggerFactory factory, String log4NetConfigFile, Boolean watch)
   at Microsoft.Extensions.Logging.Log4NetExtensions.AddLog4Net(ILoggerFactory factory, String log4NetConfigFile)
   at Microsoft.Extensions.Logging.Log4NetExtensions.AddLog4Net(ILoggerFactory factory)
   at Utilities.File.FileGetter.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) in C:\Utilities.File.FileGetter\Startup.cs:line 38
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.Start()
   at Microsoft.AspNetCore.Hosting.WindowsServices.WebHostService.OnStart(String[] args)
   at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.ServiceProcess.ServiceBase.Run(ServiceBase[] services)
   at Utilities.File.FileGetter.Program.Main(String[] args) in C:\Utilities.File.FileGetter\Program.cs:line 23

Unable to use Log4Net in windows service

I am using a windows service in ,net core and i tried to implement the library but it is not working i keep getting that ILogger is not register although i have added it in the services

Log for Net Doesn't work when published.

I'm not sure if this is related to this plugin but I'll post my issue here just in case.

I'm using log4net on .Net Core 2.0, When running from visual studio everything logs fine, However When I publish my application (locally). The file is Created, but No messages are written to the file. (When run in debug and release). Here is my configuration:

<?xml version="1.0" encoding="utf-8" ?>
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="./logs/ids4" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="RollingLogFileAppender"/>
  </root>
</log4net>

My AppSettings.Json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

In my startup file I configure logging like so:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    loggerFactory.AddLog4Net();
    //...
}

This is not a permissions issue either because the file is still created, it's just empty. My best guess would be it's related to the logging level? I would figure publishing in debug would fix this.

How can I get logging to work when published?

Note I've looked at a few other questions about this however their issue seems to be that the file was not copied to the publish directory. Log4Net.Config is in my publish directory and is this is not the issue

Match the Microsoft.Extensions.Logging LogLevels CRITICAL and TRACE to the corresponding log4net.Core Levels

Hi,

could you please extend your Microsoft.Extensions.Logging.Log4Net.AspNetCore provider supporting correct matching of the Microsoft.Extensions.Logging LogLevels CRITICAL and TRACE to the corresponding log4net.Core Levels log4net.Core.Level.Critical and log4net.Core.Level.Trace by the following changes:

in e.g. Log4NetExtensions.cs

        static public void Critical(this log4net.ILog log, object message, System.Exception exception)
        {
            log.Logger.Log(null, log4net.Core.Level.Critical, message, exception);
        }

        static public void Trace(this log4net.ILog log, object message, System.Exception exception)
        {
            log.Logger.Log(null, log4net.Core.Level.Trace, message, exception);
        }

and in Log4NetLogger.cs

 public void Log<TState>(
            LogLevel logLevel,
            EventId eventId,
            TState state,
            Exception exception,
            Func<TState, Exception, string> formatter)
        {
           ...
           ...
                switch (logLevel)
                {
                    case LogLevel.Critical:
                        this.log.Critical(message, exception);
                        break;
                    case LogLevel.Trace:
                        this.log.Trace(message, exception);
                        break;
                    case LogLevel.Debug:
                        this.log.Debug(message, exception);
                        break;
                    case LogLevel.Error:
                        this.log.Error(message, exception);
                        break;
                    case LogLevel.Information:
                        this.log.Info(message, exception);
                        break;
                    case LogLevel.Warning:
                        this.log.Warn(message, exception);
                        break;
                    default:
                        this.log.Warn($"Encountered unknown log level {logLevel}, writing out as Info.");
                        this.log.Info(message, exception);
                        break;
                }
            }
        }

?

Regards,

Installing package via nuget - Version conflict detected

I was trying to install the package from nuget in Visual Studio 15.7.2 in an ASP.NET Core 2.1 project. But it says it has a conflict with Microsoft.Extensions.Configuration.

image

It says that I have to reference the package directly to resolve the issue. But I don't want to have packages referenced directly in my project.

Aspnetcore2.0 Web Application Failed to Log

I would like to report an issue (which may or may not be the bug of this extension, I am not really sure, but I tried other open source logging extension (Serilog) that has no issue with this setup before).

  • Background
    I was trying to inject log4net for a project based on identity server but failed.

  • What is exactly the issue?
    I have setup a web project running on netcoreapp2.0 framework and setup log4net using the extension method provided in Microsoft.Extensions.Logging.Log4Net.AspNetCore nuget but have failed to log some messages.

  • How to reproduce?
    I have setup a minimal netcoreapp2.0 project to reproduce the issue, please kindly navigate to log4netaspnetcoretest (https://github.com/chanjunweimy/log4netaspnetcoretest/tree/master/NetCoreWebApplication). Follow the instruction in README.MD to reproduce the issue.

  • So what happened?
    I expect the log.txt to have the log message I added but it does not contain those.

Thank you.

Jun Wei

Didn't show method or line number for %method [%line], instead got "? [?]"

Is there any package missing?

  <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1" />
  <PackageReference Include="log4net" Version="2.0.8" />
  <PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="2.2.1" />

log4net.config below:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="ConsoleAppender" type="log4net.Appender.ManagedColoredConsoleAppender">
    <mapping>
      <level value="ERROR" />
      <foreColor value="Red" />
    </mapping>
    <mapping>
      <level value="WARN" />
      <foreColor value="Yellow" />
    </mapping>
    <mapping>
      <level value="INFO" />
      <foreColor value="White" />
    </mapping>
    <mapping>
      <level value="DEBUG" />
      <foreColor value="Green" />
    </mapping>    
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
    
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="LogFiles/"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="10"/>
    <maximumFileSize value="100MB"/>
    <datePattern value="yyyy-MM-dd'.log'" />
    <staticLogFileName value="false"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="ConsoleAppender" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>

Code in Startup.cs:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

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

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

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

Console output:

2018-07-01 13:04:40,217 INFO Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.? [?] - MESSAGE: Executed action method ProfileMgrApp.Controllers.EmployeeProfileController.Index (ProfileMgrApp), returned result Microsoft.AspNetCore.Mvc.ViewResult in 332.8077ms.
2018-07-01 13:04:40,275 INFO Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.? [?] - MESSAGE: Executing ViewResult, running view Index.
2018-07-01 13:04:40,541 INFO Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.? [?] - MESSAGE: Executed ViewResult - view Index executed in 298.2617ms.
2018-07-01 13:04:40,563 INFO Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.? [?] - MESSAGE: Executed action ProfileMgrApp.Controllers.EmployeeProfileController.Index (ProfileMgrApp) in 817.0772ms
2018-07-01 13:04:40,589 INFO Microsoft.AspNetCore.Hosting.Internal.WebHost.? [?] - MESSAGE: Request finished in 1221.1667ms 200 text/html; charset=utf-8

Dotnet Core 2 issue with log4net 2.0.8 dll

Hi Guys
I import the reference to the application in my client. The client complains that it cant find log4net 2.0.8.

The problem is the 2.0.8 dll is .net framework DLL. It wont run in a linux container. So if your trying to create a docker Linux container application your stuffed.

Arent you?

Regards
Donks

No log file is created

Minimal example:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
	loggerFactory.AddLog4Net();
	var logger = loggerFactory.CreateLogger("Global exception logger");
	logger.LogError("test");
	// No file seems to be created under \bin\Debug\netcoreapp2.0
}

Relevant infos from the .csproj file:

    <TargetFramework>netcoreapp2.0</TargetFramework>

    ...

    <PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="2.1.0" />

    ...

    <Content Update="log4net.config">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>

log4net.config:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="DebugAppender" />
  </root>
</log4net>

In the log4net.config file, also tried adding <file value="logfile.log" /> under appender.

Unable to programatically set log level

I'm having trouble setting trace level programmatically when using log4net. Logging always happens at INFO level. I have not been able to log any messages at debug level.

I'm not sure if I should be trying to set the log level somewhere in the ASP.NET Core logging framework as well as in log4net?

Any suggestions would be greatly appreciated.

This is the function that tries to set the log level.

public static void SetTraceLevel(log4net.Core.Level level)
{

            ILoggerRepository[] repos = LogManager.GetAllRepositories();
            foreach(ILoggerRepository repo in repos)
            {
                Hierarchy hierarchy = (Hierarchy)repo;
                hierarchy.Root.Level = level;
                hierarchy.Threshold = level;
                log4net.Core.ILogger[] loggers = hierarchy.GetCurrentLoggers();
                foreach(log4net.Core.ILogger logger in loggers)
                {
                    ((log4net.Repository.Hierarchy.Logger)logger).Level = level;
                }
                hierarchy.RaiseConfigurationChanged(EventArgs.Empty);
            }
 }

And this is my log4net.config file.

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
    <file type="log4net.Util.PatternString" value="%env{MY_LOG_PATH}\\%property{LogFileName}.log" />
    <appendToFile value="false" />
    <maxSizeRollBackups value="2" />
    <maximumFileSize value="2MB" />
    <rollingStyle value="Size" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout,log4net">
      <conversionPattern value="%d{HH:mm:ss,fff} [%property{ProcessId}:%-3t] %-5p [%c{1},%L] %m%n" />
    </layout>
  </appender>
  <root>
    <priority value="INFO" />
    <level value="INFO" />
  </root>
  <logger name="IdentityServer">
    <appender-ref ref="RollingLogFileAppender" />
    <level value="INFO" />
  </logger>
  <logger name="Microsoft">
    <appender-ref ref="RollingLogFileAppender" />
    <level value="INFO" />
  </logger>
  <logger name="IdentityServer4">
    <appender-ref ref="RollingLogFileAppender" />
    <level value="INFO" />
  </logger>
</log4net>

ExtensionMethod to allow CreateLogger<T> for owning class

I am wondering if something like the following would work so I can depend on the ILogProvider in my class and manually create a logger for the given type.

public static ILogger CreateLogger<T>(this ILoggerProvider provider) where T : class { return provider.CreateLogger(typeof(T).AssemblyQualifiedName); }

This would allow me to configure different settings for the different loggers (I could be missing something that is already built in-to the Logging framework).

How to access this from WCF

Hi ,

I have created a class library project where I am using this package and I can consume that class library project from.Net core application.

However, I want to access the same class library project from WCF. how can I configure ILogger from WCF service using this package?

Appreciate your help.

Thanks,
Keyur

Implementation of BeginScope<TScope>(TScope scope)

Currently method ILogger.BeginScope<TScope>(TScope scope) returns null, meaning that scope will be missed. Any plan on implement it properly?

For example. serilog remembers scopes in AsyncLocal storage with child-parent relationship, and enrich every logging event with remembered scopes. This allow to trace request path, for example, with requestId in every logged message.

log4net does have similar concept LogicalThreadContext with Properties bag and Stacks, that could be used to store additional information from scopes.

Adding this library to Log4net

Hi,

Thank you for your work, I was wondering do you have any plan to contribute this extension through pull request to log4net library?

Thanks,

Can not find log4net.config when use Log4NetProviderOptions

I Have followed the instruction in https://github.com/huorswords/Microsoft.Extensions.Logging.Log4Net.AspNetCore to configure log4net for asp net core 2.2 project.

When I run I face this error
Exception has occurred: CLR/System.IO.FileNotFoundException An exception of type 'System.IO.FileNotFoundException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Could not find file 'D:\Source\WorkSpace\BlueSpatial\BSCore\BSWeb\bin\Debug\netcoreapp2.2\log4net.config'.'

Anyone give me a help? Thanks

Invalid exception logging

Is there any reason why exception object is not passed directly into log4net methods? I'm talking about this method

Instead of passing exception into log4net method it is merged into message variable. It causes issues with layouting log entry and parsing log messages (I'm not able to separate log message from exception stacktrace)

Log exception details

At the moment Log4Net for AspNetCore seems to ignore the Exception object when logging Errors or Warnings

Trying to log to sql server

I've got my log4net.config to only contain the DebugAppender and the AdoNetAppender:

I setup the Log4Net.AspNetCore as the normal in the Startup.cs class
loggerFactory.AddLog4Net("log4net.config");

And then in the Controller constructor its expecting the log4net.Core.ILogger:
...
private readonly log4net.Core.ILogger _logger;
public ValuesController(log4net.Core.ILogger logger)
{
//log4net.aspnetcore 2.0
_logger = logger;
_logger.Log(new LoggingEvent(new LoggingEventData() { Message = "NewTest", LoggerName = "Main", Level = Level.Info }));
...

When the app starts up the following is always displayed and the AdoNetAppender doesn't load:

log4net:ERROR [AdoNetAppender] ErrorCode: GenericFailure. Failed in DoAppend
System.TypeLoadException: Could not load type 'System.Runtime.Remoting.Messaging.CallContext' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
at log4net.Util.LogicalThreadContextProperties.GetLogicalProperties()
at log4net.Util.LogicalThreadContextProperties.GetProperties(Boolean create)
at log4net.Core.LoggingEvent.CreateCompositeProperties()
at log4net.Core.LoggingEvent.CacheProperties()
at log4net.Core.LoggingEvent.FixVolatileData(FixFlags flags)
at log4net.Appender.BufferingAppenderSkeleton.Append(LoggingEvent loggingEvent)
at log4net.Appender.AppenderSkeleton.DoAppend(LoggingEvent loggingEvent)

Also of note is the AdoNetAppender is calling the sproc with no parameters. Any assistance would be helpful.

Thanks!
-jason

NullReferenceException after upgrading to 2.2.8

After upgrading to the latest version 2.2.8 I get following error:

System.AggregateException: An error occurred while writing to logger(s). (Object reference not set to an instance of an object.) ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at IEnumerable<IDisposable> Microsoft.Extensions.Logging.Scope.Registers.Log4NetEnumerableScopedRegister.AddToScope(object state)+MoveNext()
   at new Microsoft.Extensions.Logging.Scope.Log4NetScope(object scope, Log4NetScopeRegistry registry)
   at Log4NetScope Microsoft.Extensions.Logging.Scope.Log4NetScopeFactory.BeginScope<TScope>(TScope scope)
   at IDisposable Microsoft.Extensions.Logging.Log4NetLogger.BeginScope<TState>(TState state)
   at IDisposable Microsoft.Extensions.Logging.Logger.BeginScope<TState>(TState state)
   --- End of inner exception stack trace ---
   at IDisposable Microsoft.Extensions.Logging.Logger.BeginScope<TState>(TState state)
   at Context Microsoft.AspNetCore.Hosting.Internal.HostingApplication.CreateContext(IFeatureCollection contextFeatures)
   at async Task Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests<TContext>(IHttpApplication<TContext> application)
   at async Task Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync<TContext>(IHttpApplication<TContext> application)
---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
   at IEnumerable<IDisposable> Microsoft.Extensions.Logging.Scope.Registers.Log4NetEnumerableScopedRegister.AddToScope(object state)+MoveNext()
   at new Microsoft.Extensions.Logging.Scope.Log4NetScope(object scope, Log4NetScopeRegistry registry)
   at Log4NetScope Microsoft.Extensions.Logging.Scope.Log4NetScopeFactory.BeginScope<TScope>(TScope scope)
   at IDisposable Microsoft.Extensions.Logging.Log4NetLogger.BeginScope<TState>(TState state)
   at IDisposable Microsoft.Extensions.Logging.Logger.BeginScope<TState>(TState state)<---

Add support for net standard 2.0

Thanks for you nice lib. I am trying to use your lib in a net standard 2.0 project. However nuget prevents me install this lib because not support standarn 2.0.

So could you please add netstandard2.0 to solve it?

And happy new year

Error when format log string

LogInformation("{2}{1}{0}{2}", 0, 1, 2) will throw an AggregateException exception.

System.AggregateException: An error occurred while writing to logger(s). (Index (zero based) must be greater than or equal to zero and less than the size of the argument list.)

The inner string format method shouldn't check args's number just by {*}'s number simplely.

UnitTest Code:

[TestMethod]
//[ExpectedException(typeof(AggregateException))]
public void TestFormatBug()
{
	var factory = new LoggerFactory();
        Assert.IsTrue(File.Exists("log4net.xml"));
	factory.AddLog4Net("log4net.xml");
	var log = factory.CreateLogger("");
	log.LogInformation("{0}{0}", "OK"); // 应该是用{*}的个数直接和后面参数的个数比较了
}

Logging in two different files on demand

Hi,

How to logging in two different files on demand.Let say I want to log data in Login action method in one file and want to log another action methods data in another file from the below lines of code.

_logger.LogInformation("Login Action Calling");====> This has to log in one file

_logger.LogInformation("Employee Edit Action Calling");====> This has to log in another file

Modify configuration at runtime?

For security reasons, we do not include our DB connection string for ADONetAppender in log4net.config. I extended ILoggerFactory with a wrapper around a Log4NetProvider constructor:
CustomLog4NetExtension.txt

And extended Log4NetProvider with a method that sets the connection string in a way that we had working with straight log4net:
CustomLog4NetProvider.txt

The we in Startup.cs in the Configure method we do this:
loggerFactory.AddLog4NetWithAdoConnectionString( GetLoggingConnectionString()) ;

It looks like this succeeds in updating the Repository but the ADONetAppender does not work - and it does work if we include the same connection string in log4net.config.

We already thank you for the work you did in making this package available.
If you can point out mistakes I'm making or suggest a better way, that would be much appreciated, too.

Thanks,
Steve Gruverman

Add .Net Framework versions to nuget

Since .Net Framework packages built with 4.6.1+ can use .Net Core (2.0) packages, can you add additional supported versions to the csproj. I have cloned this project and just changed the csproj element to netcoreapp2.0;net462 - this seems to work. We have some third-party libraries that are only .Net Framework so we need to create libraries but still support .Net Core Logging.

Add support for environment variables

log4net has default support for environment variables, however it does not work correctly when using this extension. For instance, the file value in the appender below (note - not a full example), includes the environment variable ${LogPath}. However, this variable is not expanded at runtime and instead logs to the to the literal path ${LogPath}MyApplication.log relative to the executing assembly path. For example, C:\approot${LogPath}MyApplication.log.

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="${LogPath}MyApplication.log" />
  </appender>
</log4net>

Using environment variables with the log4net section in the an app/web.config is supported so adding this feature to this extension makes transitioning to .NET Core easier.

"Overwriting the native log4net xml configuration using the Net Core configuration system" is case sensitive.

What is the problem?

  • Expected "overrided.log" (Overided in appsettings.json) to be generated but "log.txt" (specified in log4net.config) is the one that is generated.

How to reproduce?

What is the reason?

  • I figured out the issue is because when setting attribute value, the attribute key is case sensitive.

If case sensitive is the design, then

  • I would suggest updating README.md to:
    json "Log4net": [ { "XPath": "/log4net/appender[@name='RollingFile']/file", "Attributes": { "value": "overrided.log" } }, { "XPath": "/log4net/appender[@name='RollingFile']/maximumFileSize", "Attributes": { "value": "1024KB" } } ]

any chance to support .Net Standard?

log4net supports .NET Standard 1.3 since v2.0.6. However when I install this extension from NuGet, the following error message is shown:
Package Microsoft.Extensions.Logging.Log4Net.AspNetCore 1.1.0 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package Microsoft.Extensions.Logging.Log4Net.AspNetCore 1.1.0 supports: netcoreapp1.1 (.NETCoreApp,Version=v1.1)

Double printing message

I'm seeing some strange behavior where messages are being double printed:

//start of json log
{"appName":"PvaTest","level":"ERROR","messageObject":"test","renderedMessage":"test","timestampUtc":"2019-02-21T17:37:44.1051799Z","logger":"test","thread":"1","exceptionObject":{"ClassName":"System.Exception","Message":"test","Data":null,"InnerException":null,"HelpURL":null,"StackTraceString":null,"RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":null,"HResult":-2146233088,"Source":null,"WatsonBuckets":null},"exceptionObjectString":"System.Exception: test","userName":"a\a","domain":"PvaTest.exe","identity":"","pid":45700,"machineName":"45K9VT2","workingSet":23457792,"osVersion":"Microsoft Windows NT 6.2.9200.0","properties":{"log4net:UserName":"a\a","log4net:Identity":"","CustomerId":3,"log4net:HostName":"45K9VT2"}} //end of json log
System.Exception: test // <---- where did this come from?

image

I cant figure out where this is coming from. I've set a breakpoint in my layout class and when it writes to the TextWriter that value is not there, looks like maybe its being added by this Library?

I see the same thing using the standard pattern layout:
image

It seems to only do this when an exception is passed in.

If I set these to null it fixes the problem:
image

Have you ever seen this?

Saving Log files to azure blob

Is there way to save log files to Azure blob storage using this package. If yes, can you please share configurations.

Cant load the log4net config file from the project root

Hello!

I just upgraded to version 2.2.6 from 2.2.5 and had to downgrade as I am getting an error now finding the log4net config file

System.IO.FileNotFoundException: 'Could not find file 'C:\Users\jsoto\Documents\MicroServices\BonusesPlayerMicroservice\BonusesPlayer\BonusesPlayer.Api\bin\Debug\netcoreapp2.1\log4net.config'.'

The file location is on the project root
C:\Users\jsoto\Documents\MicroServices\BonusesPlayerMicroservice\BonusesPlayer\BonusesPlayer.Api\

But for some reason now its looking in the bin\Debug\netcoreapp2.1 folder

and I just have in my startup file the no parameters add log 4 net instruction

loggerFactory.AddLog4Net();

with just downgrading from 2.2.6 to 2.2.5 the issue disappear

using dotnet verion 2.1.1

Thanks a lot!

ArgumentNullException when running with TestHost

When running the AspNet.Core application within the TestHost, an ArgumentNullException occurs:

System.ArgumentNullException : Value cannot be null.
Parameter name: repositoryAssembly
   at log4net.Core.LoggerManager.CreateRepository(Assembly repositoryAssembly, Type repositoryType)
   at Microsoft.Extensions.Logging.Log4NetProvider..ctor(String log4NetConfigFile, Func`3 exceptionFormatter)
   at YYY.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) in YYY\Startup.cs:line 337
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)
   at YYY.IntegrationTests.InvitationApiTests..ctor() in YYY.IntegrationTests\InvitationApiTests.cs:line 46
   at YYY.IntegrationTests.InvitationApiTests.InviteMethod..ctor()

Issue should be gone when Issue microsoft/vstest#649 will be fixed.

Signed assembly

I'd like to use this package in a couple of projects but am unable to, since it would need to be called by a signed assembly and is itself unsigned. Could you stick a signing key on there, perchance?

Thanks.

Log only custom messages

I have recently started to use Microsoft.Extensions.Logging.Log4Net.AspNetCore on asp.net core 2.2

I managed to successfully log my custom messages but I also see in log.txt that asp.net core events are written.
Is there any way to prevent this and just log my custom message only?

Thanks

latest version does't log to file

when in debug mode and on windows,the log file is created normaly,
but when it is deployed in centos 7, the log file can't be created. The previous version is OK .

File overwritten

When using the logging with the following config, it doesn't produce the expected results as the file gets overwritten multiple times during startup. This is due to the "appendToFile" value being false. Setting the value to "true" obviously resolves the issue however, the file is no longer overwritten on application startup as required.

I assume as each logger is created, it deletes the existing file and creates a new one.

<appender name="FileAppenderXml" type="log4net.Appender.FileAppender"> <file type="log4net.Util.PatternString" value="Log\ClientApp.xml"/> <appendToFile value="false"/> <layout type="log4net.Layout.XmlLayoutSchemaLog4j"> <locationInfo value="true"/> </layout> <param name="Encoding" value="utf-8" /> </appender>

In essence, any logging that is done prior to the last instance of the logger object being created is deleted. The expected behavior is that all the logging is recorded however, on application startup the existing file is delete (once, if present).

Support for configuration watching

Hi,

Is there a possibility to support the configuration watcher?
I think you just need to replace the call for Configure function with ConfigureAndWatch.

Thanks

Error in .NET Core 2.0 project when using <layout type="log4net.Layout.XmlLayoutSchemaLog4j" /> in log4net.Appender.UdpAppender

When use I got the error:

log4net:ERROR [UdpAppender] ErrorCode: WriteFailure. Unable to send logging event to remote host 127.0.0.1 on port 7071.
System.ArgumentException: Invalid name character in 'log4j:event'. The ':' character, hexadecimal value 0x3A, cannot be included in a name.
at System.Xml.XmlWellFormedWriter.CheckNCName(String ncname)
at System.Xml.XmlWellFormedWriter.WriteStartElement(String prefix, String localName, String ns)
at log4net.Layout.XmlLayoutSchemaLog4j.FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
at log4net.Layout.XmlLayoutBase.Format(TextWriter writer, LoggingEvent loggingEvent)
at log4net.Appender.AppenderSkeleton.RenderLoggingEvent(LoggingEvent loggingEvent)
at log4net.Appender.UdpAppender.Append(LoggingEvent loggingEvent)

This problem is not directly related with this extension but as it depends of log4net.dll it is not possible to fix it.

Results are different when executed using "dotnet vstest" vs "Test Explorer" from Visual studio

I am using log4net package inside my .Net Core 2.2 project,
In one of my test case, I am trying to compare the error which has been returned from log4net.Appender.MemoryAppender.GetEvents().Single().RenderedMessage(). When I execute from Test Explorer, the error is something like:

Thrown System.Collections.Generic.KeyNotFoundException "testMessage"\r\n at LoggingUnitTests.Log4NetLogTestsLoggingEnabled.GetStackFramesRecursive (source file unavailable)\r\n at LoggingUnitTests.Log4NetLogTestsLoggingEnabled.GetStackFrames (source file unavailable)

While using dotnet vstest the error is something like:

Thrown System.Collections.Generic.KeyNotFoundException "testMessage"\r\n at LoggingUnitTests.Log4NetLogTestsLoggingEnabled.GetStackFramesRecursive (source file unavailable)\r\n at LoggingUnitTests.Log4NetLogTestsLoggingEnabled.mytestcasename (source file unavailable)

If you will notice, the test case name i.e. mytestcasename is being added in error message string when executing from dotnet vstest. This inconsistent behavior should have been fixed.

Custom Appender not working

Hello,
I try to use custom appender on log4net but not working.Default appenders working fine.

.net core 2.0 | log4net 2.0.8 | Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 2.2.4

Here is my config :

<appender name="custom" type="APIGateway.LogAppender.TestAppenderSkeleton">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
    </layout>
</appender>
namespace APIGateway.LogAppender
{
   public class TestAppenderSkeleton : AppenderSkeleton
   {
       protected override void Append(LoggingEvent loggingEvent)
       {
           try
           {
             
           }
           catch
           {


           }

       }
   }
}

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.