Fix crash on logout
[kdenetwork.git] / ksirc / logfile.cpp
blob09e1a976f52910ce55af1ac5b9e12eadbda95f6e
1 /* This file is part of the KDE project
2 Copyright (C) 2001 Simon Hausmann <hausmann@kde.org>
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the Artistic License.
6 */
8 #include "logfile.h"
10 #include <assert.h>
12 #include <qdir.h>
13 #include <QDate>
14 #include <QDateTime>
15 //Added by qt3to4:
16 #include <QTimerEvent>
18 #include <kstandarddirs.h>
20 LogFile::LogFile( const QString &channel, const QString &server )
21 : m_channel( channel ), m_server( server ), m_file( new QFile() ),
22 m_flushTimerId( -1 )
26 LogFile::~LogFile()
28 closeLog();
29 delete m_file;
32 void LogFile::open()
34 int suffix = 1;
36 m_file->setName( makeLogFileName( m_channel, m_server ) );
38 while ( !m_file->open( QIODevice::WriteOnly | QIODevice::Append ) && suffix < 16000 ) // arbitrary limit ;)
40 m_file->setName( makeLogFileName( m_channel, m_server, suffix ) );
41 suffix++;
44 assert( m_file->isOpen() == true );
46 log( QString::fromLatin1( "### Log session started at " )
47 + QDateTime::currentDateTime().toString()
48 + QString::fromLatin1( "###\n" ) );
51 void LogFile::closeLog()
53 log( QString::fromLatin1( "### Log session terminated at " )
54 + QDateTime::currentDateTime().toString()
55 + QString::fromLatin1( "###\n" ) );
57 if ( m_flushTimerId != -1 )
58 killTimer( m_flushTimerId );
60 m_file->close();
63 void LogFile::log( const QString &message )
65 m_file->writeBlock( message.local8Bit(), message.length() );
67 if ( m_flushTimerId == -1 )
68 m_flushTimerId = startTimer( 60000 ); // flush each minute
71 void LogFile::timerEvent( QTimerEvent * )
73 if ( m_file )
74 m_file->flush();
76 killTimer( m_flushTimerId );
77 m_flushTimerId = -1;
80 QString LogFile::makeLogFileName( const QString &channel, const QString &server, int suffix )
82 QString res = channel + '_';
84 QDate dt = QDate::currentDate();
85 QString dateStr;
86 dateStr.sprintf( "%.4d_%.2d_%.2d_", dt.year(), dt.month(), dt.day() );
87 res += dateStr;
89 res += server;
91 res += ".log";
93 if ( suffix > -1 )
94 res += '.' + QString::number( suffix );
96 return locateLocal( "appdata", "logs/" + res );