SerilogFactory don't log my messages but it logs exceptions - servicestack

I want to use the SerilogFactory, the LogFactory is initialized before initializing the AppHost.
This is my startup.cs :
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var logger = new LoggerConfiguration().WriteTo.File("log.txt").CreateLogger();
LogManager.LogFactory = new SerilogFactory(logger);
app.Map("/api", api =>
{
api.UseServiceStack(new AppHost(env.ApplicationName, Configuration));
});
}
}
And this is my sample service :
public class TestService : ServiceStack.Service
{
public static ILog Log = LogManager.GetLogger(typeof(TestService));
public bool Get(GetTest request)
{
Log.Info("foo");
Log.Warn("???");
throw new System.Exception("plop");
return true;
}
}
After calling the "GetTest" request, I can see the details of the exception in my "log.txt" file but I can't see the Info "foo" or the Warm "???" in the file.
2019-07-03 18:07:55.597 +02:00 [INF] Initializing Application Tmpi.PocketTournee took 352.2006ms. No errors detected.
2019-07-03 18:08:07.446 +02:00 [ERR] ServiceBase<TRequest>::Service Exception
System.Exception: plop
at Tmpi.PocketTournee.ServiceInterface.TestService.Get(GetTest request) in C:\Projects\VS2017\PocketTournee\WebService\Sources\Tmpi.PocketTournee.ServiceInterface\TestService.cs:line 15
If I initialize the LogFactory AFTER initializing the AppHost, I can see my own logs but this time the exception details and the servicestack init info have disappeared :
2019-07-03 18:25:05.420 +02:00 [INF] foo
2019-07-03 18:25:05.434 +02:00 [WRN] ???

So I've set some breakpoint to watch the type of LogManager.LogFactory :
Before registering the first LogFactory the type of LogManager.LogFactory is ServiceStack.Logging.NullLogFactory
*After registering the first LogFactory the type of LogManager.LogFactory is of course ServiceStack.Logging.Serilog.SerilogFactory nothing wrong here
*But after AppHost initialization the type of LogManager.LogFactory is reverted to ServiceStack.NetCore.NetCoreLogFactory
Like in this code :
var logFactory = new SerilogFactory(new LoggerConfiguration()
.WriteTo.File("log.txt")
.CreateLogger());
// Here LogManager.LogFactory is {ServiceStack.Logging.NullLogFactory}
LogManager.LogFactory = logFactory;
// Here LogManager.LogFactory is {ServiceStack.Logging.Serilog.SerilogFactory}
app.Map("/api", api =>
{
api.UseServiceStack(new AppHost(env.ApplicationName, Configuration));
});
// Here LogManager.LogFactory is {ServiceStack.NetCore.NetCoreLogFactory}
LogManager.LogFactory = logFactory;

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.

Can't see logs in Azure Log Stream

In my Web Api App, I have the controller:
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
System.Diagnostics.Trace.TraceInformation("in get...");
return "value";
}
}
I want to be able to see the log "in get..." on Azure when I publish it. On Azure, in the App Service Logs I turn on Application Logging (Filesystem) and set the level to Information. In the Log Stream, when I go to the url of the method, I see in the logs:
Connecting... 2020-02-09T06:07:38 Welcome, you are now connected to
log-streaming service. The default timeout is 2 hours. Change the
timeout with the App Setting SCM_LOGSTREAM_TIMEOUT (in seconds).
2020-02-09 06:08:07.158 +00:00 [Information]
Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting
HTTP/1.1 GET
http://testapi20200208104448.azurewebsites.net/api/values/5 2020-02-09
06:08:07.159 +00:00 [Information]
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Executing
action method TestApi.Controllers.ValuesController.Get (TestApi) with
arguments (5) - ModelState is Valid 2020-02-09 06:08:07.160 +00:00
[Information] Microsoft.AspNetCore.Mvc.Internal.ObjectResultExecutor:
Executing ObjectResult, writing value
Microsoft.AspNetCore.Mvc.ControllerContext.
But I don't see my log "in get..."
This is a known issue for .NET core (but for .NET framework, it can work well).
As a workaround for .NET core web application, I suggest you can use ILogger, which can write message to Application Logs.
In Startup.cs -> Configure method, re-write Configure method like below:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//your other code
//add the following 2 lines of code.
loggerFactory.AddConsole();
loggerFactory.AddDebug();
app.UseStaticFiles();
//your other code
}
then in ValuesController:
public class ValuesController : Controller
{
private readonly ILogger _logger;
public ValuesController(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<ValuesController>();
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
//System.Diagnostics.Trace.TraceInformation("in get...");
//use ILogger here.
_logger.LogInformation("in get...");
return "value";
}
}
Ivan's answer did not fully work for me on aspnetcore 3.1, but it led me to this article, which gave me all information I needed:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1

ASP.NET CORE 2.2 Deployment Issue

I'm having the weirdest issue and I have no idea why.
When deploying our .net core 2.2 api to our local IIS server I get the following error message:
HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure
After checking the event log I this is the error that I find:
Application: dotnet.exe
CoreCLR Version: 4.6.27207.3
Description: The process was terminated due to an unhandled exception.
Exception Info: System.InvalidOperationException: No service for type 'Digitise.Infrastructure.Services.DatabaseMigrator' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Digitise.ApiBase.BaseProgram.Initialise(String[] args, IWebHost host) in C:\Projects\Digitise.AspNetCore\Digitise.ApiBase\BaseProgram.cs:line 17
at Digitise.Api.Program.Main(String[] args) in C:\Projects\Digitise.AspNetCore\Digitise.Api\Program.cs:line 27
It seems like the DI is not working correctly! The weird thing is if I run the api.exe or dotnet api.dll the API works perfectly :/
Anyone have any ideas? :)
Program.cs
public class Program
{
public static object _lock = new object();
public static bool _init = false;
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args);
Initialise(args, host);
}
public static IWebHost CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
//.UseIISIntegration()
.UseIIS()
.UseNLog()
.UseShutdownTimeout(TimeSpan.FromSeconds(10))
.Build();
public static void Initialise(string[] args, IWebHost host)
{
var logger = NLogBuilder.ConfigureNLog(Path.Combine(Directory.GetCurrentDirectory(), "NLog.config")).GetCurrentClassLogger();
try
{
logger.Debug("App init");
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
if (!_init)
{
lock (_lock)
{
if (!_init)
{
lock (_lock)
{
services.GetRequiredService<DatabaseMigrator>().Migrate();
}
}
}
}
}
catch (Exception ex)
{
logger.Error(ex, "An error occurred while starting up the app.");
throw;
}
}
host.Run();
}
catch (Exception e)
{
logger.Error(e, "Stopped app due to exception");
throw;
}
}
}
DatabaseMigrator.cs
public class DatabaseMigrator
{
private readonly TenantDbContext _tenantDbContext;
private readonly IOptions<DatabaseConfiguration> _databaseConfig;
private readonly ILogger<DatabaseMigrator> _logger;
private readonly AdminTenantDbInitialiser _adminTenantDbInitialiser;
public DatabaseMigrator(TenantDbContext tenantDbContext, IOptions<DatabaseConfiguration> databaseConfig, ILogger<DatabaseMigrator> logger, AdminTenantDbInitialiser adminTenantDbInitialiser)
{
_tenantDbContext = tenantDbContext;
_databaseConfig = databaseConfig;
_logger = logger;
_adminTenantDbInitialiser = adminTenantDbInitialiser;
}
public void Migrate()
{
//migration logic
}
}
I've just gone through a lot of pain fixing a similar problem. Pretty sure the problem is you using Directory.GetCurrentDirectory(), this does odd things when running with in-process hosting as in IIS. I replaced it with Assembly.GetExecutingAssembly().Location and all worked fine.
Clue came from Dotnet Core Multiple Startup Classes with In-Process Hosting
In my case the issue started to show up after I updated some Nuget packages. Installing the latest .NET Core SDK has helped.

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.

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

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.

Resources