代码之家  ›  专栏  ›  技术社区  ›  Andrus

如何从syslog中删除计算机和进程名称以及进程ID

  •  -3
  • Andrus  · 技术社区  · 6 月前

    Debian系统日志包含重复信息,如:

    Dec 25 09:43:28 uvn-76-202 Eeva[7192]:          at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
    Dec 25 09:43:28 uvn-76-202 Eeva[7192]:          at Program.<>c.<<Main>b__3_6>d.MoveNext() in C:\raamat\eevaweb\Store\Program.cs:line 979
    Dec 25 09:43:28 uvn-76-202 Eeva[7192]:       
    Dec 25 09:45:01 uvn-76-202 CRON[18528]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
    Dec 25 09:54:14 uvn-76-202 systemd[1]: Created slice User Slice of UID 0.
    

    如何删除服务器名称、进程名称、进程id和空格,以便输出

    Dec 25 09:43:28 at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
    Dec 25 09:43:28 at Program.<>c.<<Main>b__3_6>d.MoveNext() in C:\raamat\eevaweb\Store\Program.cs:line 979
    Dec 25 09:45:01 (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
    Dec 25 09:54:14 Created slice User Slice of UID 0.
    

    尝试在ASP。NET 9 MVC控制器

      StribBuilder sb = new();
      using StreamReader reader = new("/var/log/syslog");
      string line;
      while ((line = await reader.ReadLineAsync()) != null)
      {
        line = StrTran(line, "uvn-76-202 Eeva", "");
        line = StrTran(line, "         "), "");
        sb.AppendLine(line);
      }
    
    static string StrTran(string cSearchIn, string cSearchFor, string cReplaceWith)
    {
      StringBuilder sb = new(cSearchIn);
      return sb.Replace(cSearchFor, cReplaceWith).ToString();
    }
    

    但这只删除了部分不必要的信息。

    1 回复  |  直到 6 月前
        1
  •  2
  •   Alexander D    6 月前
    using System;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    
    public class LogProcessor
    {
    public static async Task<string> ProcessLogAsync(string logPath)
    {
        StringBuilder sb = new();
        using StreamReader reader = new(logPath);
    
        string line;
        while ((line = await reader.ReadLineAsync()) != null)
        {
            // Use regex to remove the server name, process name, and process 
    ID.
            line = Regex.Replace(line, @"\buvn-76-202\b.*?\[\d+\]:\s*", "");
    
            // Remove leading spaces (if any).
            line = line.TrimStart();
    
            sb.AppendLine(line);
        }
    
        return sb.ToString();
        }
    }
    
    
    class Program
    {
    public static async Task Main(string[] args)
    {
        string logPath = "/var/log/syslog";
        string processedLogs = await LogProcessor.ProcessLogAsync(logPath);
        Console.WriteLine(processedLogs);
        }
    }