summaryrefslogtreecommitdiff
path: root/Utility/LogFile.hs
blob: 1985b7edac7a965e735f2441629da1ee238f9d91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{- log files
 -
 - Copyright 2012 Joey Hess <joey@kitenet.net>
 -
 - Licensed under the GNU GPL version 3 or higher.
 -}

module Utility.LogFile where

import Common

import System.Posix

openLog :: FilePath -> IO Fd
openLog logfile = do
	rotateLog logfile 0
	openFd logfile WriteOnly (Just stdFileMode)
		defaultFileFlags { append = True }

rotateLog :: FilePath -> Int -> IO ()
rotateLog logfile num
	| num > maxLogs = return ()
	| otherwise = whenM (doesFileExist currfile) $ do
		rotateLog logfile (num + 1)
		renameFile currfile nextfile
  where
	currfile = filename num
	nextfile = filename (num + 1)
	filename n
		| n == 0 = logfile
		| otherwise = rotatedLog logfile n

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