packages feed

fast-logger 3.2.9 → 3.3.0

raw patch · 12 files changed

+267/−29 lines, 12 filesPVP ok

version bump matches the API change (PVP)

API changes (from Hackage documentation)

+ System.Log.FastLogger.Internal: replaceFD :: Loggers a => a -> FD -> IO ()

Files

ChangeLog.md view
@@ -1,3 +1,16 @@+## 3.3.0++`pushLogStr` now throws an `IOError` after `rmLoggerSet`.++* Replace the FD where writes are already serialized+  [#227](https://github.com/kazu-yamamoto/logger/pull/227)+* Skip empty writes in toBufIOWith+  [#230](https://github.com/kazu-yamamoto/logger/pull/230)+* Define the behavior of a removed LoggerSet+  [#229](https://github.com/kazu-yamamoto/logger/pull/229)+* Make rotate cost proportional to the existing backups+  [#228](https://github.com/kazu-yamamoto/logger/pull/228)+ ## 3.2.9  * The writer thread of SingleLogger survives write errors such as
System/Log/FastLogger/File.hs view
@@ -85,15 +85,25 @@ -- native one the file is a 'System.IO.Handle', which is shared for -- deletion, and it does. rotate :: FileLogSpec -> IO ()-rotate spec = mapM_ move srcdsts+rotate spec+    | n <= 0 = return ()+    | otherwise = do+        k <- firstMissing 0+        mapM_ (\i -> move (backup (i - 1)) (backup i)) [k, k - 1 .. 1]+        move path (backup 0)   where     path = log_file spec     n = log_backup_number spec-    dsts' = reverse . ("" :) . map (('.' :) . show) $ [0 .. n - 1]-    dsts = map (path ++) dsts'-    srcs = drop 1 dsts-    srcdsts = zip srcs dsts-    move (src, dst) = do+    backup :: Int -> FilePath+    backup i = path ++ "." ++ show i+    -- Only the backups before the first missing one need shifting,+    -- so a huge 'log_backup_number' costs nothing.+    firstMissing i+        | i >= n - 1 = return (n - 1)+        | otherwise = do+            exist <- doesFileExist (backup i)+            if exist then firstMissing (i + 1) else return i+    move src dst = do         exist <- doesFileExist src         when exist $ renameFile src dst 
System/Log/FastLogger/IO.hs view
@@ -37,11 +37,13 @@   where     loop writer = do         (len, next) <- writer buf size-        io buf len+        -- Empty steps occur, e.g. for an empty builder or around a chunk.+        when (len > 0) $ io buf len         case next of             Done -> return ()             More minSize writer'                 | size < minSize -> error "toBufIOWith: More: minSize"                 | otherwise -> loop writer'-            Chunk (PS fptr off siz) writer' ->-                withForeignPtr fptr $ \ptr -> io (ptr `plusPtr` off) siz >> loop writer'+            Chunk (PS fptr off siz) writer' -> do+                when (siz > 0) $ withForeignPtr fptr $ \ptr -> io (ptr `plusPtr` off) siz+                loop writer'
System/Log/FastLogger/LoggerSet.hs view
@@ -30,6 +30,7 @@  import Control.Concurrent (getNumCapabilities) import Control.Debounce (debounceAction, defaultDebounceSettings, mkDebounce, debounceThreadName)+import System.IO.Error (illegalOperationErrorType, ioeSetErrorString, mkIOError)  import System.Log.FastLogger.FileIO import System.Log.FastLogger.IO@@ -116,7 +117,7 @@     flush <-         mkDebounce             defaultDebounceSettings-                { debounceAction = flushLogStrRaw logger+                { debounceAction = whenOpen fdref $ flushLogStrRaw logger                 , debounceThreadName = "Loggerset of FastLogger (Debounce)"                 }     return $@@ -130,14 +131,23 @@ -- | Writing a log message to the corresponding buffer. --   If the buffer becomes full, the log messages in the buffer --   are written to its corresponding file, stdout, or stderr.+--   This throws an 'IOError' after 'rmLoggerSet'. pushLogStr :: LoggerSet -> LogStr -> IO ()-pushLogStr LoggerSet{..} logmsg = case lgrsetLogger of-    SL sl -> do-        pushLog sl logmsg-        lgrsetDebounce-    ML ml -> do-        pushLog ml logmsg-        lgrsetDebounce+pushLogStr LoggerSet{..} logmsg = do+    fd <- readIORef lgrsetFdRef+    unless (isFDValid fd) $ ioError removed+    case lgrsetLogger of+        SL sl -> do+            pushLog sl logmsg+            lgrsetDebounce+        ML ml -> do+            pushLog ml logmsg+            lgrsetDebounce+  where+    removed =+        ioeSetErrorString+            (mkIOError illegalOperationErrorType "pushLogStr" Nothing lgrsetFilePath)+            "LoggerSet already removed"  -- | Same as 'pushLogStr' but also appends a newline. pushLogStrLn :: LoggerSet -> LogStr -> IO ()@@ -152,9 +162,18 @@ --   courtesy of the auto-update package. Since version 2.2.2, this --   function can be used to force flushing outside of the debounced --   flush calls.+--+--   This does nothing after 'rmLoggerSet'. flushLogStr :: LoggerSet -> IO ()-flushLogStr LoggerSet{..} = flushLogStrRaw lgrsetLogger+flushLogStr LoggerSet{..} = whenOpen lgrsetFdRef $ flushLogStrRaw lgrsetLogger +-- The loggers are stopped by 'rmLoggerSet', which invalidates the FD,+-- and using them after that blocks forever.+whenOpen :: IORef FD -> IO () -> IO ()+whenOpen fdref act = do+    fd <- readIORef fdref+    when (isFDValid fd) act+ flushLogStrRaw :: Logger -> IO () flushLogStrRaw (SL sl) = flushAllLog sl flushLogStrRaw (ML ml) = flushAllLog ml@@ -165,12 +184,16 @@ renewLoggerSet LoggerSet{..} = case lgrsetFilePath of     Nothing -> return ()     Just file -> do-        newfd <- openFileFD file-        oldfd <- atomicModifyIORef' lgrsetFdRef (\fd -> (newfd, fd))-        closeFD oldfd+        -- A removed 'LoggerSet' has no writer to hand the FD to.+        valid <- isFDValid <$> readIORef lgrsetFdRef+        when valid $ do+            newfd <- openFileFD file+            case lgrsetLogger of+                SL sl -> replaceFD sl newfd+                ML ml -> replaceFD ml newfd  -- | Flushing the buffers, closing the internal file information---   and freeing the buffers.+--   and freeing the buffers.  This does nothing if called again. rmLoggerSet :: LoggerSet -> IO () rmLoggerSet LoggerSet{..} = do     fd <- readIORef lgrsetFdRef@@ -178,8 +201,9 @@         case lgrsetLogger of             SL sl -> stopLoggers sl             ML ml -> stopLoggers ml-        when (isJust lgrsetFilePath) $ closeFD fd-        writeIORef lgrsetFdRef invalidFD+        -- Read again: the FD may have been replaced while stopping.+        fd' <- atomicModifyIORef' lgrsetFdRef (\x -> (invalidFD, x))+        when (isJust lgrsetFilePath) $ closeFD fd'  -- | Replacing the file path in 'LoggerSet' and returning a new --   'LoggerSet' and the old file path.
System/Log/FastLogger/MultiLogger.hs view
@@ -39,6 +39,7 @@     stopLoggers = System.Log.FastLogger.MultiLogger.stopLoggers     pushLog = System.Log.FastLogger.MultiLogger.pushLog     flushAllLog = System.Log.FastLogger.MultiLogger.flushAllLog+    replaceFD = System.Log.FastLogger.MultiLogger.replaceFD  ---------------------------------------------------------------- @@ -126,3 +127,12 @@ writeBigLogStr' :: MultiLogger -> LogStr -> IO () writeBigLogStr' MultiLogger{..} logstr =     withMVar mlgrMBuffer $ \_ -> writeBigLogStr mlgrFdRef logstr++----------------------------------------------------------------++-- | Replacing the FD.  Writers hold 'mlgrMBuffer' while using the+--   FD, so the old one is not closed under them.+replaceFD :: MultiLogger -> FD -> IO ()+replaceFD MultiLogger{..} newfd = withMVar mlgrMBuffer $ \_ -> do+    oldfd <- atomicModifyIORef' mlgrFdRef (\fd -> (newfd, fd))+    closeFD oldfd
System/Log/FastLogger/SingleLogger.hs view
@@ -18,7 +18,9 @@  ---------------------------------------------------------------- -data Ent = F (MVar ()) Bool | L LogStr+-- The writer thread is the only one touching the FD, so 'R' makes+-- it replace the FD instead of locking around each write.+data Ent = F (MVar ()) Bool | L LogStr | R FD type Q = [Ent] -- writer queue  -- | A non-scale but time-ordered logger.@@ -29,12 +31,14 @@     , slgrBuffer :: Buffer     , slgrBufSize :: BufSize     , slgrFdRef :: IORef FD+    , slgrReplace :: FD -> IO ()     }  instance Loggers SingleLogger where     stopLoggers = System.Log.FastLogger.SingleLogger.stopLoggers     pushLog = System.Log.FastLogger.SingleLogger.pushLog     flushAllLog = System.Log.FastLogger.SingleLogger.flushAllLog+    replaceFD = System.Log.FastLogger.SingleLogger.replaceFD  ---------------------------------------------------------------- @@ -59,6 +63,10 @@     go (F mvar cont : msgs) = do         putMVar mvar ()         if cont then go msgs else return False+    go (R newfd : msgs) = do+        oldfd <- atomicModifyIORef' fdref (\fd -> (newfd, fd))+        dropOnSyncException $ closeFD oldfd+        go msgs     go (L msg@(LogStr len _) : msgs) = do         dropOnSyncException $             if len <= bufsize@@ -92,6 +100,10 @@             atomicModifyIORef' ref (\(old, q) -> ((mempty, fin : L old : q), ()))             wakeup             takeMVar mvar+        -- Not waiting: the writer may be far behind the pushers.+        replace newfd = do+            atomicModifyIORef' ref (\(old, q) -> ((mempty, R newfd : L old : q), ()))+            wakeup     return $         SingleLogger             { slgrRef = ref@@ -100,6 +112,7 @@             , slgrBuffer = buf             , slgrBufSize = bufsize             , slgrFdRef = fdref+            , slgrReplace = replace             }  ----------------------------------------------------------------@@ -126,3 +139,8 @@ stopLoggers SingleLogger{..} = do     slgrFlush False     freeBuffer slgrBuffer++-- | Replacing the FD after the messages pushed so far are written.+--   This returns before that happens.+replaceFD :: SingleLogger -> FD -> IO ()+replaceFD SingleLogger{..} = slgrReplace
System/Log/FastLogger/Write.hs view
@@ -43,3 +43,5 @@     stopLoggers :: a -> IO ()     pushLog :: a -> LogStr -> IO ()     flushAllLog :: a -> IO ()+    -- | Replacing the FD and closing the old one, which is not in use.+    replaceFD :: a -> FD -> IO ()
fast-logger.cabal view
@@ -1,6 +1,6 @@ cabal-version:      >=1.10 name:               fast-logger-version:            3.2.9+version:            3.3.0 license:            BSD3 license-file:       LICENSE maintainer:         Kazu Yamamoto <kazu@iij.ad.jp>@@ -65,7 +65,12 @@     main-is:          Spec.hs     build-tools:      hspec-discover >=2.6     hs-source-dirs:   test-    other-modules:    FastLoggerSpec+    other-modules:+        BufIOSpec+        ClosedSpec+        FastLoggerSpec+        RotateSpec+     default-language: Haskell2010     ghc-options:      -Wall -threaded -rtsopts -with-rtsopts=-N     build-depends:
+ test/BufIOSpec.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE OverloadedStrings #-}++module BufIOSpec where++import qualified Data.ByteString.Char8 as BS+import Data.IORef+import System.Log.FastLogger+import System.Log.FastLogger.Internal+import Test.Hspec++spec :: Spec+spec = describe "toBufIOWith (#81)" $ do+    it "does not write an empty builder" $+        lengths mempty `shouldReturn` []+    it "does not write empty steps around a big chunk" $+        lengths (toLogStr (BS.replicate 100000 'x')) `shouldReturn` [100000]+    it "writes a small message once" $+        lengths "hello\n" `shouldReturn` [6]++-- The lengths passed to the writing action.+lengths :: LogStr -> IO [Int]+lengths (LogStr len builder) = do+    ref <- newIORef []+    buf <- getBuffer (max 1 len)+    toBufIOWith buf len (\_ n -> modifyIORef ref (n :)) builder+    freeBuffer buf+    reverse <$> readIORef ref
+ test/ClosedSpec.hs view
@@ -0,0 +1,30 @@+module ClosedSpec where++import Control.Exception (finally)+import System.Directory (doesFileExist, removeFile)+import System.IO.Error (isIllegalOperation)+import System.Log.FastLogger+import System.Timeout (timeout)+import Test.Hspec++spec :: Spec+spec = describe "removed LoggerSet (#166)" $ do+    it "fails only on pushing with the single logger" $ closed (Just 1)+    it "fails only on pushing with the multi logger" $ closed Nothing++closed :: Maybe Int -> IO ()+closed mn = flip finally cleanup $ do+    cleanup+    lgrset <- newFileLoggerSetN 64 mn logFile+    rmLoggerSet lgrset+    pushLogStr lgrset (toLogStr "after removal\n") `shouldThrow` isIllegalOperation+    timeout 3000000 (flushLogStr lgrset) `shouldReturn` Just ()+    timeout 3000000 (rmLoggerSet lgrset) `shouldReturn` Just ()+    readFile logFile `shouldReturn` ""+  where+    cleanup = do+        exist <- doesFileExist logFile+        if exist then removeFile logFile else return ()++logFile :: FilePath+logFile = "test/closed.txt"
test/FastLoggerSpec.hs view
@@ -7,16 +7,17 @@ import Control.Applicative ((<$>)) #endif import Control.Concurrent (getNumCapabilities)-import Control.Concurrent.Async (forConcurrently_)+import Control.Concurrent.Async (concurrently, forConcurrently_) import Control.Exception (finally) import Control.Monad (forM_, when) import qualified Data.ByteString.Char8 as BS+import Data.IORef (newIORef, readIORef, writeIORef) import Data.List (sort) #if !MIN_VERSION_base(4,11,0) import Data.Monoid ((<>)) #endif import Data.String (IsString (fromString))-import System.Directory (doesFileExist, removeFile)+import System.Directory (doesFileExist, removeFile, renameFile) #if !defined(mingw32_HOST_OS) import qualified GHC.IO.FD as FD import GHC.IO.IOMode (IOMode (ReadMode))@@ -59,6 +60,12 @@         it "maintains the ordering of log messages" logOrdering         it "survives write errors" survivesWriteErrors +    describe "renewLoggerSet" $ do+        it "does not close the FD under the single logger's writer" $+            renewWhileLogging (Just 1)+        it "does not close the FD under the multi logger's writers" $+            renewWhileLogging Nothing+ tempFile :: FilePath tempFile = "test/temp.txt" @@ -132,4 +139,39 @@     mapM_ (\_ -> pushLogStr lgrset msg) [1 .. 100 :: Int]     timeout 3000000 (flushLogStr lgrset) `shouldReturn` Just ()     timeout 3000000 (rmLoggerSet lgrset) `shouldReturn` Just ()+#endif++-- Rotates the way 'tryRotate' does while messages are being written.+-- An FD closed under a writer makes a write fail with EBADF.+renewWhileLogging :: Maybe Int -> IO ()+#if defined(mingw32_HOST_OS)+-- An open file cannot be renamed under the POSIX I/O manager.+renewWhileLogging _ = pendingWith "renaming an open file"+#else+renewWhileLogging mn = flip finally (mapM_ cleanup files) $ do+    mapM_ cleanup files+    lgrset <- newFileLoggerSetN 64 mn tempFile+    renewed <- newIORef False+    let logger i = do+            pushLogStr lgrset (toLogStr (show i) <> "\n")+            fin <- readIORef renewed+            if fin && i >= 20000 then return i else logger (i + 1)+        renewer = do+            forM_ backups $ \backup -> do+                renameFile tempFile backup+                renewLoggerSet lgrset+            writeIORef renewed True+    res <- timeout 30000000 $ do+        (pushed, _) <- concurrently (logger (1 :: Int)) renewer+        flushLogStr lgrset+        rmLoggerSet lgrset+        return pushed+    case res of+        Nothing -> expectationFailure "flushing or removing the logger set hung"+        Just pushed -> do+            xs <- concatMap BS.lines <$> mapM BS.readFile files+            length xs `shouldBe` pushed+  where+    backups = [tempFile <> "." <> show i | i <- [1 .. 500 :: Int]]+    files = tempFile : backups #endif
+ test/RotateSpec.hs view
@@ -0,0 +1,55 @@+module RotateSpec where++import Control.Exception (IOException, finally, try)+import Control.Monad (forM, forM_, void)+import qualified Data.ByteString.Char8 as BS+import System.Directory (+    createDirectoryIfMissing,+    doesFileExist,+    removeDirectoryRecursive,+ )+import System.Log.FastLogger+import System.Timeout (timeout)+import Test.Hspec++spec :: Spec+spec = describe "rotate" $ do+    it "shifts the backups and drops the oldest" $+        withFiles ["", ".0", ".1", ".2"] $ do+            rotate (FileLogSpec logFile 0 3)+            contents ["", ".0", ".1", ".2"]+                `shouldReturn` [Nothing, Just "", Just ".0", Just ".1"]+    it "stops shifting at the first missing backup" $+        withFiles ["", ".0", ".2"] $ do+            rotate (FileLogSpec logFile 0 3)+            contents ["", ".0", ".1", ".2"]+                `shouldReturn` [Nothing, Just "", Just ".0", Just ".2"]+    it "does not blow up with maxBound backups (#212)" $+        withFiles ["", ".0"] $ do+            timeout 3000000 (rotate (FileLogSpec logFile 0 maxBound))+                `shouldReturn` Just ()+            contents ["", ".0", ".1"]+                `shouldReturn` [Nothing, Just "", Just ".0"]++dir :: FilePath+dir = "test/rotate"++logFile :: FilePath+logFile = dir ++ "/log"++-- Each file holds its own suffix so that moves can be traced.+withFiles :: [String] -> IO () -> IO ()+withFiles sfxs act = flip finally cleanup $ do+    cleanup+    createDirectoryIfMissing True dir+    forM_ sfxs $ \s -> writeFile (logFile ++ s) s+    act+  where+    cleanup =+        void (try (removeDirectoryRecursive dir) :: IO (Either IOException ()))++contents :: [String] -> IO [Maybe String]+contents sfxs = forM sfxs $ \s -> do+    let f = logFile ++ s+    exist <- doesFileExist f+    if exist then Just . BS.unpack <$> BS.readFile f else return Nothing