Logs to a file (a primitive way)

I found sihl/core_log.ml at c6786f25424c1b9f40ce656e908bd31515f1cd09 · oxidizing/sihl · GitHub and wonder what a primitive way to log to a file would be.

I need to keep stdout clean and not show any log message under all circumstances.

Redirect from stdout to a file?

I do a cgi and stdout is the response – logging has to go to a separate file. Not even stderr as I want debug logs not to taint the webserver error log in case. And I would like to funnel logging through Logs.

I don’t know about logs but it should be relatively easy to keep an open file handle and print log messages there.

1 Like

opam - logs - I like the loglevel approach. But maybe I will do without and pass around the channel, yes.

1 Like

I believe logs support logging to a file via Format. See Logs (logs.Logs)

3 Likes

I’ve found logs very ergonomic and easy to work with. I tend to pull it in via Bos, which has a very nice interface to OS interactions. Opening the Bos_setup module also does default logs configuration, and I find all quite painless and pleasant.

1 Like

thanks @yawaramin @beajeanm @shonfeder, I took a middle ground and went along the lines of opam - logs (using the loglevels and logging call style) but base writing almost directly on out_channel. (I need a log rotation on top)

I was struggling with lost messages however – the logfile remained empty until I flushed after each log message.

Is that known behaviour that writing to a channel (with Printf.fprintf) doesn’t necessarily end up in the file? Even when closed quickly.

1 Like

Channels are buffered so they don’t get written unless they are flushed.

that’s why I mentioned close_out which says:

Close the given channel, flushing all buffered write operations.

You must Printf.printf with “%!” at the end of your format string,
to be sure that the log is flushed to file.

That’s what I do in dolog:

1 Like

that’s what I do. Still I wonder who eats the buffer once I don’t. Since I close the file (implicit flush) milliseconds later.