2012-06-11 04:39:09 +00:00
|
|
|
{- log files
|
|
|
|
-
|
|
|
|
- Copyright 2012 Joey Hess <joey@kitenet.net>
|
|
|
|
-
|
|
|
|
- Licensed under the GNU GPL version 3 or higher.
|
|
|
|
-}
|
|
|
|
|
2013-05-10 21:29:59 +00:00
|
|
|
{-# LANGUAGE CPP #-}
|
|
|
|
|
2012-06-11 04:39:09 +00:00
|
|
|
module Utility.LogFile where
|
|
|
|
|
|
|
|
import Common
|
|
|
|
|
2013-05-11 20:03:00 +00:00
|
|
|
import System.Posix.Types
|
2012-06-11 04:39:09 +00:00
|
|
|
|
|
|
|
openLog :: FilePath -> IO Fd
|
2013-08-02 16:27:32 +00:00
|
|
|
#ifndef mingw32_HOST_OS
|
2012-06-11 04:39:09 +00:00
|
|
|
openLog logfile = do
|
2013-03-01 17:30:48 +00:00
|
|
|
rotateLog logfile
|
2012-06-11 04:39:09 +00:00
|
|
|
openFd logfile WriteOnly (Just stdFileMode)
|
|
|
|
defaultFileFlags { append = True }
|
2013-05-11 20:03:00 +00:00
|
|
|
#else
|
|
|
|
openLog = error "openLog TODO"
|
|
|
|
#endif
|
2012-06-11 04:39:09 +00:00
|
|
|
|
2013-03-01 17:30:48 +00:00
|
|
|
rotateLog :: FilePath -> IO ()
|
|
|
|
rotateLog logfile = go 0
|
2012-12-13 04:24:19 +00:00
|
|
|
where
|
2013-03-01 17:30:48 +00:00
|
|
|
go num
|
|
|
|
| num > maxLogs = return ()
|
|
|
|
| otherwise = whenM (doesFileExist currfile) $ do
|
|
|
|
go (num + 1)
|
|
|
|
renameFile currfile nextfile
|
|
|
|
where
|
|
|
|
currfile = filename num
|
|
|
|
nextfile = filename (num + 1)
|
|
|
|
filename n
|
|
|
|
| n == 0 = logfile
|
|
|
|
| otherwise = rotatedLog logfile n
|
2013-01-15 17:52:35 +00: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 17:30:48 +00:00
|
|
|
|
|
|
|
redirLog :: Fd -> IO ()
|
2013-08-02 16:27:32 +00:00
|
|
|
#ifndef mingw32_HOST_OS
|
2013-03-01 17:30:48 +00:00
|
|
|
redirLog logfd = do
|
|
|
|
mapM_ (redir logfd) [stdOutput, stdError]
|
|
|
|
closeFd logfd
|
2013-05-11 20:03:00 +00:00
|
|
|
#else
|
|
|
|
redirLog _ = error "redirLog TODO"
|
|
|
|
#endif
|
2013-03-01 17:30:48 +00:00
|
|
|
|
|
|
|
redir :: Fd -> Fd -> IO ()
|
2013-08-04 17:54:09 +00:00
|
|
|
#ifndef mingw32_HOST_OS
|
2013-03-01 17:30:48 +00:00
|
|
|
redir newh h = do
|
|
|
|
closeFd h
|
|
|
|
void $ dupTo newh h
|
2013-05-11 20:03:00 +00:00
|
|
|
#else
|
|
|
|
redir _ _ = error "redir TODO"
|
|
|
|
#endif
|