Logs functions fixes

This commit is contained in:
pokamest 2022-01-30 17:35:57 +03:00
parent 95fe09489c
commit d24f6ae064
15 changed files with 240 additions and 39 deletions

View file

@ -9,7 +9,7 @@
QFile Log::m_file;
QTextStream Log::m_textStream;
QString Log::m_logFileName;
QString Log::m_logFileName = QString("%1.log").arg(SERVICE_NAME);
void debugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
@ -22,20 +22,20 @@ void debugMessageHandler(QtMsgType type, const QMessageLogContext& context, cons
std::cout << qFormatLogMessage(type, context, msg).toStdString() << std::endl << std::flush;
}
bool Log::initialize()
bool Log::init()
{
if (m_file.isOpen()) return true;
QString path = Utils::systemLogPath();
QDir appDir(path);
if (!appDir.mkpath(path)) {
return false;
}
m_logFileName = QString("%1.log").arg(SERVICE_NAME);
qSetMessagePattern("%{time yyyy-MM-dd hh:mm:ss} %{type} %{message}");
m_file.setFileName(appDir.filePath(m_logFileName));
if (!m_file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
if (!m_file.open(QIODevice::Append)) {
qWarning() << "Cannot open log file:" << m_logFileName;
return false;
}
@ -46,8 +46,59 @@ bool Log::initialize()
return true;
}
void Log::deinit()
{
m_file.close();
m_textStream.setDevice(nullptr);
qInstallMessageHandler(nullptr);
}
QString Log::serviceLogFileNamePath()
{
return m_file.fileName();
}
void Log::clearLogs()
{
bool isLogActive = m_file.isOpen();
m_file.close();
QString path = Utils::systemLogPath();
QDir appDir(path);
QFile file;
file.setFileName(appDir.filePath(m_logFileName));
file.open(QIODevice::WriteOnly | QIODevice::Truncate);
file.resize(0);
file.close();
if (isLogActive) {
init();
}
}
void Log::cleanUp()
{
clearLogs();
deinit();
QString path = Utils::systemLogPath();
QDir appDir(path);
{
QFile file;
file.setFileName(appDir.filePath(m_logFileName));
file.remove();
}
{
QFile file;
file.setFileName(appDir.filePath("openvpn.log"));
file.remove();
}
#ifdef Q_OS_WINDOWS
QDir dir(Utils::systemLogPath());
dir.removeRecursively();
#endif
}

View file

@ -9,9 +9,14 @@
class Log
{
public:
static bool initialize();
static bool init();
static void deinit();
static QString serviceLogFileNamePath();
static void clearLogs();
static void cleanUp();
private:
friend void debugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg);

View file

@ -20,7 +20,7 @@ int main(int argc, char **argv)
{
Utils::initializePath(Utils::systemLogPath());
Log::initialize();
Log::init();
if (argc == 2) {
qInfo() << "Started as console application";