blammo icon indicating copy to clipboard operation
blammo copied to clipboard

Adding log rotation and corresponding settings

Open andrew-wja opened this issue 1 year ago • 7 comments

In the Blammo log settings, there is no control supplied for log rotation, though it is provided by upstream fast-logger -- is this something that's on the roadmap (would you be open to a PR adding control of this?)

I have a fairly straightforward use-case where I have a web application which would like to serve its own logs into a scrollable text view using a simple time-range query like /log?since=timestamp&until=timestamp

Implementing this the naive way by logging to a file and then filtering that file for messages with timestamps in the correct range results in terrible performance, and gets slower as the application runs and the log gets larger.

Rather than any fancy complex solution, it seems the simplest and best thing to do would be to set the logger to rotate log files (say every N minutes), which places a bound on the search. Then the timestamp range requested maps to a finite subset of those rotating log files, and only the ones not wholly contained in the time range need to be filtered at all (rotated log sections wholly contained in the time range can just be dumped straight out to the viewer over HTTP).

andrew-wja avatar Mar 15 '25 21:03 andrew-wja

I think it's generally reasonable to expose features that fast-logger supports.

Would it work for you if there was only a setLoggerSomething function you could use, or would you want a way to do this via LOGGER_SOMETHING environment variable too -- such as LOG_DESTINATION=<path>;<rotation settings>?

I've just recently added the setLoggerReformat function, to customize the (re)formatter -- but that feature doesn't interact with LOG_FORMAT at all. It feels like a landmine to use this function to "bypass" LOG_FORMAT, but it does mean the feature could ship easily without any concern for compatibility or "schema" for the environment variables. So I may want to play the same trick here.

As an aside,

Rather than any fancy complex solution, it seems the simplest

Yeah, I understand that. My apps tend to already be deployed somewhere semi-fancy (containerized on AWS), so shipping logs to (e.g.) CloudWatch would already be happening, which can then be searched easily to build that view -- but if you're not already in such an environment, doing so just for this feature doesn't seem reasonable.

pbrisbin avatar Mar 17 '25 13:03 pbrisbin

Oh, I hadn't actually even considered the environment variable control surface! Hmm. I think the way I most commonly see log rotation done, it tends to follow a pattern that could have a simple enable/disable variable.

Typically the declared log file path is used for the running log, and successively older rotated log snapshots get suffixes indicating their offset in "rotation intervals" from the running log. So if the user could supply a seed suffix and a suffix increment function, that seems like enough to roll with. This might be defaulted to simply 0 and +1 to yield app.log, app.log.0, app.log.1 and so on. So any MonadPlus with a Show instance might work here for the user to tell us how they want suffixes generated.

I think the awkwardness of supplying a suffix and an increment function via environment variable text contents kind of rules it out as a viable control surface here, so setLogger* functions seem plenty for configuring rotation.

One nice aspect to the "supplied log path is always the current running log" approach is that all loggers can be rotating loggers, rather than special casing -- and "non rotating" instances simply have an infinite rotation interval. We could encode that in a nice way I think. If we wrap the concrete suffix type in a Maybe, Nothing means no rotation. If someone wants to stop rotating their logs at a defined point, their increment function could return Nothing as opposed to Just nextSuffix, which seems like a nice feature to have for the low price of a design choice! If your application is entering a period where you would like log rotation to stop (such as when you begin a shutdown that might be extended), and you'd like to make sure a log rotation doesn't happen in there, you can signal your intent to the logger cleanly.

I'll put together a small PR to anchor the discussion 🙂

andrew-wja avatar Mar 19 '25 08:03 andrew-wja

Tagging on one more comment to remind future-me of this concern -- typically applications top out at a configurable maximum number of preserved log segments, so we might have app.log and app.log.N for 0 <= N <= X where the user would like to supply X as well as the seed and increment. That's implementable as a simple maximum and seems like it would require almost zero extra code to handle. If Nothing, then we keep rotating the log for the lifetime of the application, if Just X we keep at most X log segments, cascading the offsets as normal each time a rotation is triggered, and rotating the least recent log either out of existence, or into colder storage. In the case of colder storage, the user could supply a simple handler for "freezing" a log section -- for example, pushing it to an upstream service (in the case of segmented logging where you want to quickly log to local files, and then every-so-often push larger batched log sections upstream to, for example, a metrics service).

andrew-wja avatar Mar 19 '25 09:03 andrew-wja

Hmm, maybe I was confused. I thought you were saying fast-logger supported log rotation. As in, if we just called some function on the underlying FastLogger.LoggerSet, it would Do The Thing. I think exposing a way through Blammo to have that function called and result in The Thing happening would be totally reasonable -- in other words, anything fast-logger itself supports is fair game to be exposed through Blammo interfaces.

But your further comments make it seem like Blammo would actually implement the log rotation, and it would just be updating the LoggerSet with a new filename when it deems that necessary. I'd be less interested in taking all that on within the Blammo library.

Do I have that right?

If so, I still think we can eventually meet the need of Blammo-users having rotation, but I would slice it up differently. For example, what about implementing a separate fast-logger-rotation package to house all this logic, then expose its functions through Blammo's interfaces as way for Blammo users to use it. Could that make sense?

pbrisbin avatar Mar 25 '25 17:03 pbrisbin

Sorry, I got a bit saturated with day job stuff and I haven't had a chance to look at this in a while. That makes sense to me!

You have that right, fast-logger exposes the necessary primitives to allow log rotation to be implemented by a client of the library, but it does not implement log rotation in the library itself. It is implemented in some examples, and it appears relatively straightforward, but it requires a design change in Blammo, which wraps LoggerSet and adds the assumption that the LoggerSet is fixed for the lifetime of the application, which doesn't appear to have been specifically necessary, but only poses any problems when log rotation becomes a desired feature.

The core of the issue is that Blammo's monad fixes the LoggerSet in use when the logger is created, while log rotation as in the fast-logger examples relies on being able to change the LoggerSet that's passed to the fast-logger API functions.

I am not sure if this functionality is large enough to require a separate package, but certainly it should be in a separate logging monad, IMO. Blammo's logging monad currently has only immutable state, which simplifies things a lot.

To do log rotation, the logging monad needs to treat the LoggerSet that is active as a true mutable state variable, and it also needs a monadic operation to perform the log rotation that the user can invoke, which should swap out the currently-active LoggerSet for a new user-provided LoggerSet, or alternatively, perhaps create a new LoggerSet from some defaults/configuration and swap that in for the currently-active one.

andrew-wja avatar Jun 11 '25 09:06 andrew-wja

I am not sure if this functionality is large enough to require a separate package

For me, it's less about size (I don't mind relatively small packages) and more about isolating concerns.

I'm picturing a type like SizedLoggerSet which holds some immutable facts (like what is the maximum size we're maintaining, the original file name that was used, etc) and some mutable facts (like the active LoggerSet, the current size that's been logged so far, etc). Then you re-implement pushLoggerStr{,Ln} such that they do the logging to the current logger-set but also accomplish the rotation if necessary.

Personally, I'd want to explore making this somewhat generic. Bounding it on size (bytes or lines) is a choice. The app.log.N pattern is a choice. You'd want some settings mechanism for that. Ideally, I'd want the types to be flexible enough to support things you might not think of yet. Something like...

data RotatedLoggerSet c s = RotatedLoggerSet
  { config :: c
  , state :: IORef (LoggerSet, s)
  }

pushRotatedLogStr
  :: (c -> (LoggerSet, s) -> Maybe (LoggerSet, s))
  -- ^ Given the immutable config and the current state, possibly update that state (i.e. rotate)
  -> RotatedLoggerSet c s
  -> LogStr
  -> IO ()
pushRotatedLogStr updateState rls str = do
  state <- readIORef rls.state
  FastLogger.pushLogStr (fst state) str
  traverse_ (writeIORef rls.state) $ updateState rls.config state

This is a flexible base you can wrap up for your current use-case easily:

type SizedLoggerSet = RotatedLoggerSet
  Natural             -- maximum lines, at which to rotate
  (FilePath, Natural) -- current filename and number of lines logged so far

newSizedLoggerSet :: FilePath -> Natural -> IO SizedLoggerSet
newSizedLoggerSet name maxSize = do
  ls <- newFileLoggerSet defaultBufSize name
  ref <- newIORef (ls, (name, 0))
  pure $ RotatedLoggerSet maxSize ref

pushLogStrLn :: SizedLoggerSet -> LogStr -> IO ()
pushLogStrLn = pushRotatedLogStrLn $ \maxSize (ls, (name, curSize)) -> do
  let newSize = curSize + 1
  guard $ newSize > maxSize
  let
    newName = mkNewName name
    (newLs, _) = replaceLoggerSet ls newName
  pure (newLs, (newName, newSize))

mkNewName :: FilePath -> FilePath
mkNewName = _ -- If path ends in .N, make it .N+1. Otherwise, make it .1

This all feels wholly unrelated to Blammo, but also not something to upstream to fast-logger (IMO). So a fast-logger-rotation package feels appropriate to me: give yourself space to experiment, without having to worry about another project's release cycle or maintainer review. I'd probably use more records instead of tuples, for example, but you don't have to follow that opinion if you don't want to.

When and/if that was all done, I think it would be a relatively simple update to have Blammo hold a SizedLoggerSet instead of a LoggerSet (or any other RotatedLoggerSet type), and there you go. Then we can focus on what's important for that concern, such as the ENV configuration interface.

pbrisbin avatar Jun 11 '25 16:06 pbrisbin

I'm going to close this, as it sounds like there is a path forward that doesn't (yet) involve work on Blammo's plate.

To recap:

  • fast-logger's responsibility is actual logging functionality
  • Blammo's responsibility is to wrap that in a nicer interface; good defaults, ENV-based settings, etc

Automatic log rotation is a responsibility that sits in the middle, and so should be a third package built on fast-logger and used by Blammo. When/if that package exists, we can open an issue (or PR) here to discuss using it.

pbrisbin avatar Dec 08 '25 16:12 pbrisbin