How to set log4net's log file location in autofac? - log4net

I am now adding controller log by following this post: Using Autofac to inject log4net into controller
After doing that, I can get my application run correctly. Below are the details:
LogInjectionModule here:
public class LogInjectionModule:Module
{
protected override void AttachToComponentRegistration(Autofac.Core.IComponentRegistry componentRegistry, Autofac.Core.IComponentRegistration registration)
{
registration.Preparing += OnComponentPreparing;
}
static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
var t = e.Component.Activator.LimitType;
e.Parameters = e.Parameters.Union(new[]
{
new ResolvedParameter((p, i) => p.ParameterType == typeof(ILog), (p, i) => LogManager.GetLogger(t))
});
}
}
DependencyRegister here:
private void RegisterDependency()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerHttpRequest();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();
builder.RegisterType<BookContext>().As<IDbContext>().SingleInstance().PreserveExistingDefaults();
builder.RegisterType<ManagerRepository>().As<IManager>().InstancePerHttpRequest();
builder.RegisterType<BookLendRepository>().As<IBookLend>().InstancePerHttpRequest();
builder.RegisterType<BookPlaceRepository>().As<IBookPlace>().InstancePerHttpRequest();
builder.RegisterType<BookRepository>().As<IBook>().InstancePerHttpRequest();
builder.RegisterType<BookTypeRepository>().As<IBookType>().InstancePerHttpRequest();
builder.RegisterType<StudentRepository>().As<IStudent>().InstancePerHttpRequest();
builder.RegisterType<ManagerService>().As<IManagerService>().InstancePerHttpRequest();
builder.RegisterModule(new LogInjectionModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
MyController here:
public HomeController(
IManagerService managerService
,ILog logger
)
{
this.managerService = managerService;
this.logger = logger;
}
private readonly IManagerService managerService;
private readonly ILog logger;
public ActionResult Index(Manager manager)
{
logger.Info("test");
return View();
}
And when I debug to logger.Info("test") , I can get the log instance. But the problem is , where is the log file's location? is there any config for the integrated log4net that I can decide where to put the log file?

The question isn't related to Autofac. Log4net is a standalone library. You can read more about log4net on its homepage and how to configure it here.

Related

No job functions found. Try making your job classes and methods public whilst using a CLI-deployed function

I appreciate there are a few of these questions, but I'm fairly certain I've been through everything and have reached the 'what the hell' point.
I'm pushing out a v3 Function to Azure and having no luck in actually getting the Function to.....function. I'm worried that the Azure CLI task is breaking something.
The startup of my function is:
[assembly: FunctionsStartup(typeof(TestFunction.Startup))]
namespace TestFunction
{
public class Startup : FunctionsStartup
{
public IConfiguration Configuration { get; }
public override void Configure(IFunctionsHostBuilder builder)
{
// Config
var config = new ConfigurationBuilder().AddEnvironmentVariables().Build();
// Level
LogEventLevel logLevel;
switch (config["SerilogLoggingLevel"])
{
case "Error":
logLevel = LogEventLevel.Error;
break;
case "Warning":
logLevel = LogEventLevel.Warning;
break;
case "Information":
logLevel = LogEventLevel.Information;
break;
case "Debug":
logLevel = LogEventLevel.Debug;
break;
default:
logLevel = LogEventLevel.Verbose;
break;
}
// Load the logger from the settings
var logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Error)
.Enrich.FromLogContext()
.WriteTo.AzureAnalytics(workspaceId: config["SerilogWorkspaceId"],
authenticationId: config["SerilogAuthId"],
logName: config["SerilogName"],
restrictedToMinimumLevel: logLevel)
.CreateLogger();
// Add the logger
builder.Services.AddLogging(c => c.AddSerilog(logger));
// Starting
Log.Information("Starting up!");
}
}
}
And the function inside:
public class TestEventTrigger
{
private readonly IConfiguration _configuration;
public TestEventTrigger(
IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
[FunctionName("TestEvent")]
public void Run([ServiceBusTrigger("testevent", Connection = "ServiceBusConnectionString")]Message incomingMessage)
{
Log.Debug("Message received: '" + System.Text.Encoding.Default.GetString(incomingMessage.Body) + "'");
}
}
I'm fairly certain I have all the packages installed. Browsing to the Function seems to be OK via the web.
Nothing shows in the custom log in Log Analytics, either. The table does get created though.
The release is done using:
az functionapp deployment source config-zip
Turns out, it wasn't pushing to the app correctly, but failing silently. Fixed the deployment, and all is good.

No logging with configuration made in code using latest version of slf4net (1.0.0)

I'm using the slf4net.log4net nuget package to handle logging in a project. Because it must be possible for the loglevel to change at runtime, I made the configuration in code. The issue is that this code works fine in slf4net.log4net version 0.1.32.1 but when I upgrade it to version 1.0.0, the logfile is created, but the logs are not present on the logfile. I've created a dummy project to show this issue. I do not see how I can add a zip file here, so I'll just post the code here. It is a console app in net framework 4.7.2;
class Program
{
private static string GetLoggingPath()
{
var path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData,
Environment.SpecialFolderOption.DoNotVerify), "LoggingTesting");
Directory.CreateDirectory(path);
return path;
}
static void Main(string[] args)
{
var layout = new PatternLayout
{
ConversionPattern = "%d{ABSOLUTE}: %message %newline"
};
layout.ActivateOptions();
var fileAppender = new RollingFileAppender();
fileAppender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date;
fileAppender.Layout = layout;
var path = GetLoggingPath();
fileAppender.File = path + System.IO.Path.DirectorySeparatorChar + "LISlogging_.txt";
fileAppender.AppendToFile = true;
fileAppender.PreserveLogFileNameExtension = true;
fileAppender.StaticLogFileName = false;
fileAppender.DatePattern = "yyyy-MM-dd";
fileAppender.MaxSizeRollBackups = 10;
fileAppender.ActivateOptions();
ILoggerRepository repository = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly());
BasicConfigurator.Configure(repository, fileAppender);
var root = (repository as Hierarchy)?.Root;
if (root == null) return;
root.Level = log4net.Core.Level.All;
// Create log4net ILoggerFactory and set the resolver
var factory = new slf4net.log4net.Log4netLoggerFactory();
var resolver = new SimpleFactoryResolver(factory);
slf4net.LoggerFactory.SetFactoryResolver(resolver);
// trigger logging
var log = slf4net.LoggerFactory.GetLogger(typeof(Program));
log.Info("log this line");
}
}
public class SimpleFactoryResolver : IFactoryResolver
{
private readonly slf4net.ILoggerFactory _factory;
public SimpleFactoryResolver(slf4net.ILoggerFactory factory)
{
_factory = factory;
}
public slf4net.ILoggerFactory GetFactory()
{
return _factory;
}
}
This dummy project was created in .net framework, but I need this in a .net core project. That is why I need to version 1.0.0 .
I've also post this issue on the github page of slf4net (because it looks like a bug) : https://github.com/ef-labs/slf4net/issues/6
My main question for here on stack overflow is if there is a workaround so this can work with slf4net.log4net version 1.0.0
I've found a workaround for this. Maybe not the cleanest solution but it works. If anyone knows a cleaner solution please add it here.
When looking at the slf4net.log4net code I found out that when it tries to configure log4net it uses xml files or config files, which is a nightmare if you want to set the loglevel at runtime. You can pass a customconfigurator as parameter of the Log4netLoggerFactory . This customconfigurator needs to implement IXmlConfigurator.
The CustomConfigurator I've made accepts an IAppender and a loglevel (log4net.Core.Level). In the implementation of the Configure(ICollection(ILoggerRepository repository) method. I've set the root log level and Configured with the BasicConfigurator.
The CustomConfigurator looks like this:
public class CustomConfigurator: IXmlConfigurator
{
private readonly IAppender _appender;
private readonly log4net.Core.Level _logLevel;
public CustomConfigurator(IAppender appender, log4net.Core.Level logLevel)
{
_appender = appender;
_logLevel = logLevel;
}
public ICollection Configure(ILoggerRepository repository)
{
var root = (repository as Hierarchy)?.Root;
if (root != null)
{
root.Level = _logLevel;
}
return BasicConfigurator.Configure(repository, _appender);
}
public ICollection Configure(ILoggerRepository repository, XmlElement element)
{
return XmlConfigurator.Configure(repository, element);
}
public ICollection Configure(ILoggerRepository repository, FileInfo configFile)
{
return XmlConfigurator.Configure(repository, configFile);
}
public ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
{
return XmlConfigurator.ConfigureAndWatch(repository, configFile);
}
}
Now you can create an appender in code like shown in the question (until fileappender.ActivateOptions) Then when constructing the log4netLoggerFactory you pass an instance of CustomConfigurator which takes the fileAppender and a loglevel as parameter.
var factory = new slf4net.log4net.Log4netLoggerFactory(new CustomConfigurator(fileAppender, Level.All));
var resolver = new SimpleFactoryResolver(factory);
slf4net.LoggerFactory.SetFactoryResolver(resolver);
This should work.

Autofac interceptor not working for some classes

I have to do some extra logic layer on existing classes. I'm using autofac.
The project is Windows service having also Kestrel server. Program.cs e.g.
void Main(string[] args) {
var customQueue = new CustomQueue();
var someClass = new SomeClass(customQueue);
var randomClass = new RandomClass();
// do some logic here with using declared instances
var server = new Server(someClass, randomClass);
server.Start();
}
And here is the Server.cs
class Server {
private IWebHost _host;
public Server(SomeClass cls, RandomClass cls1) {
// set to fields
}
void Start() {
_host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services =>
{
services.AddAutoFac(); // first as per doc in order to scaffold 'ConfigureContainer'?
services.AddSingleton(someClass); // fields
services.AddSingleton(randomClass); // fields
})
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration(...)
.ConfigureLogging(...);
.UseStartup<Startuo>()
.Build();
_host.StartAsync();
}
}
Startup.cs
public class Startup
{
public ILifetimeScope AutofacContainer { get; private set; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// create a container-builder and register dependencies
var builder = new ContainerBuilder();
// populate the service-descriptors added to `IServiceCollection`
// BEFORE you add things to Autofac so that the Autofac
// registrations can override stuff in the `IServiceCollection`
// as needed
builder.Populate(services);
builder.RegisterType<SomeClass>()
.As<ISomeClass>()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(SomeClassInterceptor));
builder.Register(_ => new SomeClassInterceptor());
AutofacContainer = builder.Build();
return new AutofacServiceProvider(AutofacContainer);
}
}
And last SomeClassInterceptor.cs
public class SomeClassInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
if (invocation.ReturnValue is Task taskResult)
{
taskResult.ContinueWith(
t =>
{
Console.WriteLine("OOHH YEAHH");
}, TaskContinuationOptions.None);
}
else
{
Console.WriteLine("WOW");
}
}
catch (Exception ex)
{
Console.WriteLine("EXCEPTIOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNN");
}
}
}
I've tried with Named and Typed registration with having Intercept(...) attribute but still no success. Nothing gets triggered.
Also ISomeClass is inheriting other interfaces, I've tried setting .As<>() also with those but no.
What am I missing?
In order to let the interceptor works. The class should be build by Autofac.
services.AddAutofac();
services.AddSingleton(someClass);
services.AddSingleton(randomClass);
In your case you configure Autofac using the AddAutofac method then add SomeClass as a singleton using the AddSingleton which will override the Autofac configuration. There is no way that Autofac can inject the interceptor in it.
If you want to register SomeClass as singleton you should register it using the SingleInstance() method
builder.RegisterType<SomeClass>()
.As<ISomeClass>()
.SingleInstance()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(SomeClassInterceptor));

System.IO.InvalidDataException : ServiceStackHost.Instance has already been set (BasicAppHost)

I'm getting an error when i try to run some tests on my servicestack web service.
I'm using ServiceStack 4.5.8 and Nunit 3.5. The solution was created initially from a ServiceStackVS template.
The error, which appears on a number of tests, is
System.IO.InvalidDataException : ServiceStackHost.Instance has already been set (BasicAppHost)</br>
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.</br>
at ServiceStack.ServiceStackHost.Init()</br>
at MyApp.Tests.EchoServiceUnitTests.OneTimeSetup() in </br>
C:\Repos\MyApp\Myapp\MyApp.Tests\EchoServiceUnitTests.cs:line 45 </br>
--TearDown</br>
at MyApp.Tests.EchoServiceUnitTests.TestFixtureTearDown() in </br>C:\Repos\MyApp\MyApp\MyApp.Tests\EchoServiceUnitTests.cs:line 54
One of the tests that regularly generates this error is
namespace Tests
{
[TestFixture]
public class EchoServiceUnitTests
{
private ServiceStackHost appHost;
[OneTimeSetUp]
public void OneTimeSetup()
{
this.appHost = new BasicAppHost(typeof(EchoService).Assembly).Init();
}
[OneTimeTearDown]
public void TestFixtureTearDown()
{
this.appHost.Dispose();
}
[Test]
public void TestService()
{
const string Message = "Hello";
var service = this.appHost.Container.Resolve <EchoService>();
var response = (EchoResponse)service.Any(new Echo
{
Message = Message
});
Assert.That(response.Message,
Is.EqualTo(Message));
}
}
}
the service for this is
namespace ServiceInterface
{
public class EchoService : Service
{
public object Any(Echo request)
{
return new EchoResponse {Message = request.Message};
}
}
}
[Route("/Echo")]
[Route("/Echo/{Message}")]
public class Echo : IReturn<EchoResponse>
{
public string Message { get; set; }
}
public class EchoResponse : IHasResponseStatus
{
public EchoResponse()
{
this.ResponseStatus = new ResponseStatus();
}
public string Message { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
And finally my apphost
namespace MyApplication
{
using System;
using Funq;
using ServiceInterface;
using ServiceModel.Validators;
using ServiceStack;
using ServiceStack.Admin;
using ServiceStack.Api.Swagger;
using ServiceStack.Caching;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.Logging.NLogger;
using ServiceStack.MsgPack;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.SqlServer.Converters;
using ServiceStack.ProtoBuf;
using ServiceStack.Razor;
using ServiceStack.Validation;
using ServiceStack.VirtualPath;
using ServiceStack.Wire;
public class AppHost : AppHostBase
{
public static ILog Log = LogManager.GetLogger(typeof(AppHost));
public AppHost()
: base("MyApp",
typeof(HelloService).Assembly) { }
public override void Configure(Container container)
{
LogManager.LogFactory = new NLogFactory();
Log = LogManager.GetLogger(this.GetType());
this.Plugins.Add(new RazorFormat());
this.Plugins.Add(new PostmanFeature());
this.Plugins.Add(new SwaggerFeature());
this.Plugins.Add(new AdminFeature());
var ormSettings = new AppSettings();
container.Register <ICacheClient>(new MemoryCacheClient());
var dbFactory = new OrmLiteConnectionFactory(ormSettings.GetString("SqlDbConnection"),
SqlServerDialect.Provider);
dbFactory.RegisterConnection("Database2",
ormSettings.GetString("Sql2Connection"),
SqlServerDialect.Provider);
SqlServerDialect.Provider.RegisterConverter<DateTime?>(new SqlServerDateTimeConverter());
this.Plugins.Add(new RequestLogsFeature
{
RequestLogger = new CsvRequestLogger(files: new FileSystemVirtualPathProvider(this,
this.Config.WebHostPhysicalPath),
requestLogsPattern: "requestlogs/{year}-{month}/{year}-{month}-{day}.csv",
errorLogsPattern: "requestlogs/{year}-{month}/{year}-{month}-{day}-errors.csv",
appendEvery: TimeSpan.FromSeconds(1)),
EnableRequestBodyTracking = true,
EnableResponseTracking = true,
EnableErrorTracking = true,
});
this.Plugins.Add(new AutoQueryDataFeature
{
MaxLimit = 1000
});
this.Plugins.Add(new AutoQueryFeature());
var sse = new ServerEventsFeature
{
StreamPath = "/event-stream",
HeartbeatPath = "/event-heartbeat",
UnRegisterPath = "/event-unregister",
SubscribersPath = "/event-subscribers",
LimitToAuthenticatedUsers = false,
IdleTimeout = TimeSpan.FromSeconds(30),
HeartbeatInterval = TimeSpan.FromSeconds(10),
NotifyChannelOfSubscriptions = true,
};
this.Plugins.Add(sse);
Plugins.Add(new AdminFeature());
Plugins.Add(new WireFormat());
Plugins.Add(new MsgPackFormat());
Plugins.Add(new ProtoBufFormat());
}
}
}
I've tried a variety of suggestions including making the apphost in the test static, but nothing seems to work for me. I then tried the following test which also generated the same error which suggests to me that there is something in the apphost which is wrong but I can't see what.
[TestFixture(Category = "AppHost")]
public class AppHostTests
{
/// <summary>
/// The app host doesnt throw exception.
/// </summary>
[Test]
public void AppHostDoesntThrowException()
{
var apphost = new AppHost();
Assert.That(() => apphost.Init(),
Throws.Nothing);
}
}
The tests that generate this error whether I am using NCRUNCH (set to run one at a time) or if I use resharpers run all tests. It's generally the same tests that generate this error, though that seems to vary. In all cases, if I then run the tests manually they all pass.
You can only have 1 AppHost initialized and running at the same time where somehow NCrunch test is being run whilst there is another AppHost still in use. Maybe you can try debugging and setting a breakpoint that checks if ServiceStackHost.Instance is not null before trying to initialize another AppHost.
Note the AppHostBase is an ASP.NET Web App which may be causing the interference if it's running in the same project as the unit tests. If you want an integration test use AppSelfHostBase instead which you would use in place of BasicAppHost where you'd want to run a full integration test.

Disable spring boot auditing in a jhipster generated application

I would like to disable/limit auditing (CustomAuditEventRepository) in an application generated using jhipster.
How can I do this?
Modify CustomAuditEventRepository so that it does nothing in add(), this is generated code, it's yours so you can do whatever you want with it.
Options 1: Disable audit event of spring actuator. Adding config properties to application.yml file:
management:
auditevents:
enabled: false
Refer: AuditAutoConfiguration
#Configuration(proxyBeanMethods = false)
#ConditionalOnBean(AuditEventRepository.class)
#ConditionalOnProperty(prefix = "management.auditevents", name = "enabled", matchIfMissing = true)
public class AuditAutoConfiguration {
...
}
Options 2: Add custom AuditListener bean
#Bean
public MyAuditListener auditListener() {
return new MyAuditListener();
}
public class MyAuditListener extends AbstractAuditListener {
private static final Log logger = LogFactory.getLog(MyAuditListener.class);
public MyAuditListener() {
...
}
#Override
protected void onAuditEvent(AuditEvent event) {
...
}
}

Resources