kazu-yamamoto / logger

A fast logging system for Haskell
159 stars 68 forks source link

[monad-logger] LogPrefix newtype #95

Closed parsonsmatt closed 8 years ago

parsonsmatt commented 8 years ago

We use log prefixes at work to help grep through logs. I've made a newtype instance that is sufficiently general that I'd like to make it available. If you'd like to have this in MonadLogger, then I'd be happy to submit a PR, otherwise I'll just upload it to Hackage.

This is the bulk of the code:

newtype LogPrefix m a = LogPrefix { runLogPrefix :: ReaderT Text m a }
    deriving (Functor, Applicative, Monad, MonadTrans)

instance MonadLogger m => MonadLogger (LogPrefix m) where
    monadLoggerLog loc src lvl msg = LogPrefix $ ReaderT $ \prefix ->
        monadLoggerLog loc src lvl (toLogStr prefix <> toLogStr msg)

prefixLogs :: MonadLogger m => Text -> LogPrefix m a -> m a
prefixLogs prefix action =
    flip runReaderT (mconcat ["[",prefix, "] "]) $ runLogPrefix action

with usage like

foo :: MonadLogger m => m ()
foo = $(logDebug) "foo"

lawl :: IO ()
lawl = do
    putStrLn "starting:"
    runStdoutLoggingT $ do
        foo
        "foo" `prefixLogs` do
            "nested" `prefixLogs` foo

which has the output

starting:
[Debug] foo
[Debug] [foo] [nested] foo
snoyberg commented 8 years ago

It definitely looks useful. For now, I'd say keep it in a separate package so that it can be easily updated without worrying about affecting the major version of monad-logger. If you'd like to submit a doc PR to include a link to this package from the monad-logger description, that would be great.

parsonsmatt commented 8 years ago

:+1: