gpt4 book ai didi

linux - SQL 日志在 asp net core 2.1 的 linux 服务器中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:03 25 4
gpt4 key购买 nike

我正在创建 dotnet 核心 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 - SQL 日志在 asp net core 2.1 的 linux 服务器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com