2012-06-11 00:39:09 -04:00
|
|
|
{- log files
|
|
|
|
-
|
2015-01-21 12:50:09 -04:00
|
|
|
- Copyright 2012 Joey Hess <id@joeyh.name>
|
2012-06-11 00:39:09 -04:00
|
|
|
-
|
2014-05-10 11:01:27 -03:00
|
|
|
- License: BSD-2-clause
|
2012-06-11 00:39:09 -04:00
|
|
|
-}
|
|
|
|
|
2013-05-10 16:29:59 -05:00
|
|
|
{-# LANGUAGE CPP #-}
|
|
|
|
|
2019-11-21 15:38:06 -04:00
|
|
|
module Utility.LogFile (
|
|
|
|
openLog,
|
|
|
|
listLogs,
|
|
|
|
maxLogs,
|
|
|
|
#ifndef mingw32_HOST_OS
|
|
|
|
redirLog,
|
|
|
|
redir,
|
|
|
|
#endif
|
|
|
|
) where
|
2012-06-11 00:39:09 -04:00
|
|
|
|
|
|
|
import Common
|
2022-07-12 14:53:32 -04:00
|
|
|
import Utility.RawFilePath
|
2012-06-11 00:39:09 -04:00
|
|
|
|
2014-02-25 14:09:39 -04:00
|
|
|
#ifndef mingw32_HOST_OS
|
2013-05-11 15:03:00 -05:00
|
|
|
import System.Posix.Types
|
2017-12-31 16:08:31 -04:00
|
|
|
import System.Posix.IO
|
2014-02-25 14:09:39 -04:00
|
|
|
#endif
|
2012-06-11 00:39:09 -04:00
|
|
|
|
2014-06-17 19:10:51 -04:00
|
|
|
openLog :: FilePath -> IO Handle
|
2012-06-11 00:39:09 -04:00
|
|
|
openLog logfile = do
|
2013-03-01 13:30:48 -04:00
|
|
|
rotateLog logfile
|
2014-06-17 19:10:51 -04:00
|
|
|
openFile logfile AppendMode
|
2012-06-11 00:39:09 -04:00
|
|
|
|
2013-03-01 13:30:48 -04:00
|
|
|
rotateLog :: FilePath -> IO ()
|
|
|
|
rotateLog logfile = go 0
|
2012-12-13 00:24:19 -04:00
|
|
|
where
|
2013-03-01 13:30:48 -04:00
|
|
|
go num
|
|
|
|
| num > maxLogs = return ()
|
|
|
|
| otherwise = whenM (doesFileExist currfile) $ do
|
|
|
|
go (num + 1)
|
2022-07-12 14:53:32 -04:00
|
|
|
rename (toRawFilePath currfile) (toRawFilePath nextfile)
|
2013-03-01 13:30:48 -04:00
|
|
|
where
|
|
|
|
currfile = filename num
|
|
|
|
nextfile = filename (num + 1)
|
|
|
|
filename n
|
|
|
|
| n == 0 = logfile
|
|
|
|
| otherwise = rotatedLog logfile n
|
2013-01-15 13:52:35 -04:00
|
|
|
|
|
|
|
rotatedLog :: FilePath -> Int -> FilePath
|
|
|
|
rotatedLog logfile n = logfile ++ "." ++ show n
|
|
|
|
|
|
|
|
{- Lists most recent logs last. -}
|
|
|
|
listLogs :: FilePath -> IO [FilePath]
|
|
|
|
listLogs logfile = filterM doesFileExist $ reverse $
|
|
|
|
logfile : map (rotatedLog logfile) [1..maxLogs]
|
|
|
|
|
|
|
|
maxLogs :: Int
|
|
|
|
maxLogs = 9
|
2013-03-01 13:30:48 -04:00
|
|
|
|
2013-08-02 12:27:32 -04:00
|
|
|
#ifndef mingw32_HOST_OS
|
2014-02-11 13:18:59 -04:00
|
|
|
redirLog :: Fd -> IO ()
|
2013-03-01 13:30:48 -04:00
|
|
|
redirLog logfd = do
|
|
|
|
mapM_ (redir logfd) [stdOutput, stdError]
|
|
|
|
closeFd logfd
|
|
|
|
|
|
|
|
redir :: Fd -> Fd -> IO ()
|
|
|
|
redir newh h = do
|
|
|
|
closeFd h
|
|
|
|
void $ dupTo newh h
|
2013-05-11 15:03:00 -05:00
|
|
|
#endif
|