添加日志

This commit is contained in:
zpc 2024-07-09 16:24:10 +08:00
parent edf737dc74
commit 3e4cf7c554
5 changed files with 87 additions and 15 deletions

View File

@ -1,4 +1,11 @@
using System.Diagnostics; using CodeRelease.Model;
using Serilog;
using System;
using System.Diagnostics;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace CodeRelease.BLL namespace CodeRelease.BLL
{ {
@ -32,6 +39,7 @@ namespace CodeRelease.BLL
// 绑定输出和错误数据接收事件 // 绑定输出和错误数据接收事件
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{ {
Log.Logger.Information("linux执行出错命令{command},sender:{sender}Output:{e}", command, sender, e);
if (!string.IsNullOrEmpty(e.Data)) if (!string.IsNullOrEmpty(e.Data))
{ {
Console.WriteLine($"Output: {e.Data}"); Console.WriteLine($"Output: {e.Data}");
@ -41,6 +49,7 @@ namespace CodeRelease.BLL
process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
{ {
Log.Logger.Information("linux执行出错命令{command},sender:{sender}Output:{e}", command, sender, e);
if (!string.IsNullOrEmpty(e.Data)) if (!string.IsNullOrEmpty(e.Data))
{ {
Console.WriteLine($"Error: {e.Data}"); Console.WriteLine($"Error: {e.Data}");
@ -59,13 +68,14 @@ namespace CodeRelease.BLL
await process.WaitForExitAsync(); await process.WaitForExitAsync();
// 输出退出代码 // 输出退出代码
Console.WriteLine($"Process exited with code {process.ExitCode}"); //Console.WriteLine($"Process exited with code {process.ExitCode}");
Log.Logger.Information($"执行结束 {process.ExitCode}");
exitCode = process.ExitCode; exitCode = process.ExitCode;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Exception: {ex.Message}"); Log.Logger.Information($"执行出现异常结束 {ex.Message}");
} }
return new { exitCode, outputDataReceived, errorDataReceived }; return new { exitCode, outputDataReceived, errorDataReceived };
} }

View File

@ -8,6 +8,12 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.Text.Json" Version="8.0.3" /> <PackageReference Include="System.Text.Json" Version="8.0.3" />
</ItemGroup> </ItemGroup>

View File

@ -8,6 +8,8 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using Serilog;
using System; using System;
@ -17,7 +19,7 @@ namespace CodeRelease.Controllers
[Route("api/[controller]/[Action]")] [Route("api/[controller]/[Action]")]
[ApiController] [ApiController]
public class PublishController : ControllerBase public class PublishController() : ControllerBase
{ {
[HttpGet] [HttpGet]
[HttpPost] [HttpPost]
@ -42,6 +44,7 @@ namespace CodeRelease.Controllers
/// <returns></returns> /// <returns></returns>
public async Task<object> ReleaseAction([FromBody] object data, [FromServices] GiteaWebhookConfigModel giteaWebhookConfig) public async Task<object> ReleaseAction([FromBody] object data, [FromServices] GiteaWebhookConfigModel giteaWebhookConfig)
{ {
Log.Logger.Information("执行发布接口,参数{data}", data);
JsonSerializerSettings settings = new JsonSerializerSettings JsonSerializerSettings settings = new JsonSerializerSettings
{ {
//MaxDepth = 64 // 设置一个足够大的值,默认值是 32 //MaxDepth = 64 // 设置一个足够大的值,默认值是 32
@ -85,18 +88,11 @@ namespace CodeRelease.Controllers
else if (!string.IsNullOrEmpty(releaseAction.Release.TargetCommitish)) else if (!string.IsNullOrEmpty(releaseAction.Release.TargetCommitish))
{ {
var version = releaseAction.Release.TagName; var version = releaseAction.Release.TagName;
var download = giteaWebhookConfig.BrowserDownloadFileUrl + version + "/";
if (!Directory.Exists(download))
{
Directory.CreateDirectory(download);
}
FileDownloader fileDownloader = new FileDownloader();
//giteaWebhookConfig.BrowserDownloadFileUrl.Replace("{version}", version);
var mingling = giteaWebhookConfig.MakeFile var mingling = giteaWebhookConfig.MakeFile
.Replace("{version}", version) .Replace("{version}", version)
.Replace("{dir_file_path}", download + "/") //.Replace("{dir_file_path}", download + "/")
.Replace("{target_commitish}", releaseAction.Release.TargetCommitish); .Replace("{target_commitish}", releaseAction.Release.TargetCommitish);
Log.Logger.Information("执行linux命令{mingling}", mingling);
LinuxExecuteCommand linuxExecuteCommand = new LinuxExecuteCommand(); LinuxExecuteCommand linuxExecuteCommand = new LinuxExecuteCommand();
//make public version=0.0.1 dir_file_path=/ //make public version=0.0.1 dir_file_path=/
var obj = await linuxExecuteCommand.ExecuteCommand(mingling); var obj = await linuxExecuteCommand.ExecuteCommand(mingling);

View File

@ -3,9 +3,34 @@ using CodeRelease.Utile;
using System.Diagnostics; using System.Diagnostics;
using System.Reflection; using System.Reflection;
using Serilog;
using Microsoft.Extensions.Configuration;
using Serilog.Events;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
//.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Log.Logger = new LoggerConfiguration()
//.SetBasePath(Directory.GetCurrentDirectory())
//.AddJsonFile("appsettings.json")
.WriteTo.Console()
.WriteTo.Debug()
.WriteTo.File("../output/Logs/clog-.txt", LogEventLevel.Debug, rollingInterval: RollingInterval.Day)
.CreateLogger();
builder.Logging.ClearProviders(); // 清空默认的日志记录器
builder.Logging.AddConsole();
builder.Logging.AddSerilog();
builder.Services.AddSerilog();
builder.Host.UseSerilog();
logger.Information("启动项目");
// Add services to the container. // Add services to the container.
var giteaWebhookConfigModelList = builder.Configuration.GetSection("GiteaWebhookConfig").Get<List<GiteaWebhookConfigModel>>() ?? new List<GiteaWebhookConfigModel>(); var giteaWebhookConfigModelList = builder.Configuration.GetSection("GiteaWebhookConfig").Get<List<GiteaWebhookConfigModel>>() ?? new List<GiteaWebhookConfigModel>();
builder.Services.AddSingleton(giteaWebhookConfigModelList); builder.Services.AddSingleton(giteaWebhookConfigModelList);
@ -28,6 +53,7 @@ app.UseAuthorization();
app.MapControllers(); app.MapControllers();
app.UseMiddleware<GiteaWebhookConfigMiddleware>(); app.UseMiddleware<GiteaWebhookConfigMiddleware>();
app.UseSerilogRequestLogging();
app.MapGet("/", () => app.MapGet("/", () =>
{ {
return "请求成功"; return "请求成功";

View File

@ -5,11 +5,45 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
//
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "../output/Logs/log-.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Destructure": [
{
"Name": "ToMaximumDepth",
"Args": { "maximumDestructuringDepth": 4 }
},
{
"Name": "ToMaximumStringLength",
"Args": { "maximumStringLength": 100 }
},
{
"Name": "ToMaximumCollectionCount",
"Args": { "maximumCollectionCount": 10 }
}
],
"Properties": {
"Application": "Sample"
}
},
"AllowedHosts": "*", "AllowedHosts": "*",
"Kestrel": { "Kestrel": {
"Endpoints": { "Endpoints": {
"Http": { "Http": {
"Url": "http://*:5240" "Url": "http://*:82"
} }
} }
}, },