我正在创建dotnet core 2.1项目。我使用了serilogs。在我的Windows机器上,它可以正常工作。但是在托管它之后,serilogs无法正常工作。不创建日志文件夹和日志文件。我将其托管在ubuntu 18.04版本服务器中。
我通过手动创建日志文件夹尝试了它,并赋予它读取写入权限
sudo chmod 775 /var/app/logs
sudo chown www-data /var/app/logs
这是程序类中的代码
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
.WriteTo.RollingFile(@"logs\log-{Date}.log", fileSizeLimitBytes: null, retainedFileCountLimit: null)
.CreateLogger();
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(builder =>
{
builder.SetMinimumLevel(LogLevel.Warning);
builder.AddFilter("ApiServer", LogLevel.Debug);
builder.AddSerilog();
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>();
}
这是我的启动类代码
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(s => s.UseMySql(Configuration.GetConnectionString("DefaultConnection"))
.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddCors();
services.AddAutoMapper();
services.AddTransient<Seed>();
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddScoped<IDatingRepository, DatingRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddScoped<LogUserActivity>();
IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
{
opt.Password.RequireDigit = false;
opt.Password.RequiredLength = 4;
opt.Password.RequireNonAlphanumeric = false;
opt.Password.RequireUppercase = false;
});
builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
builder.AddEntityFrameworkStores<DataContext>();
builder.AddRoleValidator<RoleValidator<Role>>();
builder.AddRoleManager<RoleManager<Role>>();
builder.AddSignInManager<SignInManager<User>>();
// services.AddAuthorization(options => {
// options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
// options.AddPolicy("SuperAdminPhotoRole", policy => policy.RequireRole("SuperAdmin"));
// });
// services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"))
.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
// app.UseHsts();
}
// app.UseHttpsRedirection();
seeder.SeedUsers();
// app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseAuthentication();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Fallback", action = "Index" }
);
});
}
}
这是我使用日志的方式
public class PhotosController : ControllerBase
{
private readonly ILogger<PhotosController> _logger;
public PhotosController(ILogger<PhotosController> logger
)
{
_logger = logger;
}
[HttpPost("{id}/setMain")]
public async Task<IActionResult> SetMainPhoto(Guid id)
{
try
{
_logger.LogDebug("Starting to change main photo");
}
catch(Exception e) {
_logger.LogError("An error occurs while changing photo");
}}}
请帮我解决这个问题。这在Windows机器上工作正常。只有在托管后才发生
最佳答案
在您的Program.cs
文件中,您需要
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().UseSerilog();
重要的部分是
.UseSerilog()
关于linux - Serilogs在aspnet core 2.1中的linux服务器中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53906470/