查看 Windows 安全事件日志的最小 F# 示例

Minimal F# example to watch the Windows security Event Log

这从不向控制台打印任何事件(在“侦听新的安全事件...”之后),尽管当我启动事件查看器应用程序时它显示安全事件正在进入。关于我可以做什么的想法错了?

open System
open System.Diagnostics
open System.Security.Principal
open System.Threading

let logName = "security"

let DumpEventLog desc =
  use log = new System.Diagnostics.EventLog (logName, desc)
  log.EnableRaisingEvents <- true;
  printfn "listening for new security events...";
  log.EntryWritten.Add (fun ent ->
    let ent = ent.Entry in
    printfn "entry written: %d %s %s" ent.InstanceId (ent.TimeGenerated.ToString())
      ent.Message);
  
[<EntryPoint>]
let main _argv =
  let isAdministrator =
    let id = WindowsIdentity.GetCurrent () in
    let p = WindowsPrincipal id in
    p.IsInRole WindowsBuiltInRole.Administrator
  in
  let () =
    if not isAdministrator
    then printfn "need admin privs to run!"
    else DumpEventLog "."
  in
  while true do
    Thread.Sleep 5000
  done;
  0

我觉得跟你的程序写法有关系。例如,当 DumpEventLog() 退出时,日志将被处理 - 但随后程序会休眠五秒钟。我不明白它如何捕捉到那个状态下的事件。

这对我有用:

open System.Diagnostics
open System.Threading

[<EntryPoint>]
let main _argv =
    use log = new EventLog ("security", ".")
    log.EnableRaisingEvents <- true
    printfn "listening for new security events..."

    log.EntryWritten.Add (fun e -> 
        printfn "Entry written: %d %O %s" e.Entry.InstanceId e.Entry.TimeGenerated e.Entry.Message)

    Thread.Sleep Timeout.Infinite
    
    0