Skip to content

Commit

Permalink
fix: partially revert "Enable application log" to "Log to file"
Browse files Browse the repository at this point in the history
  • Loading branch information
shenlebantongying authored Feb 3, 2025
1 parent 057380b commit 0aedff4
Show file tree
Hide file tree
Showing 9 changed files with 97 additions and 104 deletions.
1 change: 1 addition & 0 deletions .clang-format
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ IndentExternBlock: AfterExternBlock
IndentWidth: 2
IndentWrappedFunctionNames: false
# InsertBraces: false
InsertNewlineAtEOF: true
InsertTrailingCommas: None
KeepEmptyLinesAtTheStartOfBlocks: true
LambdaBodyIndentation: Signature
Expand Down
2 changes: 0 additions & 2 deletions src/common/logfileptr.cc

This file was deleted.

3 changes: 0 additions & 3 deletions src/common/logfileptr.hh

This file was deleted.

78 changes: 78 additions & 0 deletions src/logger.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#include "config.hh"
#include "logger.hh"
#include <QDateTime>
#include <QFile>
#include <QGlobalStatic>
#include <QMutexLocker>

QFile logFile;
QMutex logFileMutex; // Logging could happen in any threads!

void logToFileMessageHander( QtMsgType type, const QMessageLogContext & context, const QString & mess )
{
QString strTime = QDateTime::currentDateTime().toString( "MM-dd hh:mm:ss" );
QString message = QString( "%1 %2\r\n" ).arg( strTime, mess );
QMutexLocker _( &logFileMutex );

if ( logFile.isOpen() ) {
switch ( type ) {
case QtDebugMsg:
message.prepend( "Debug: " );
break;
case QtWarningMsg:
message.prepend( "Warning: " );
break;
case QtCriticalMsg:
message.prepend( "Critical: " );
break;
case QtFatalMsg:
message.prepend( "Fatal: " );
logFile.write( message.toUtf8() );
logFile.flush();
abort();
case QtInfoMsg:
message.insert( 0, "Info: " );
break;
}

logFile.write( message.toUtf8() );
logFile.flush();

return;
}
else {
fprintf( stderr, "log file failed to open\n!" );
fprintf( stderr, "%s\n", message.toUtf8().constData() );
}
}

namespace Logger {
void switchLoggingMethod( bool logToFile )
{
QMutexLocker _( &logFileMutex );
if ( logToFile ) {
if ( !logFile.isOpen() ) {
logFile.setFileName( Config::getConfigDir() + "gd_log.txt" );
if ( !logFile.open( QFile::WriteOnly ) ) {
qDebug() << "Failed to open log file!";
return;
};
}
qInstallMessageHandler( logToFileMessageHander );
}
else {
if ( logFile.isOpen() ) {
logFile.flush();
}
qInstallMessageHandler( nullptr ); // restore the default one
}
}

void closeLogFile()
{
if ( logFile.isOpen() ) {
logFile.flush();
logFile.close();
}
}
} // namespace Logger
7 changes: 7 additions & 0 deletions src/logger.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#pragma once

/// Manage Logging, mainly for switching to log-to-file because of Windows
namespace Logger {
void switchLoggingMethod( bool logToFile );
void closeLogFile();
}; // namespace Logger
97 changes: 5 additions & 92 deletions src/main.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */

#include "config.hh"
#include "logfileptr.hh"
#include "logger.hh"
#include "mainwindow.hh"
#include "termination.hh"
#include "version.hh"
Expand All @@ -14,11 +14,9 @@
#include <QMutex>
#include <QSessionManager>
#include <QString>
#include <QStringBuilder>
#include <QtWebEngineCore/QWebEngineUrlScheme>
#include <stdio.h>
#include <QStyleFactory>

#if defined( Q_OS_UNIX )
#include <clocale>
#include "unix/ksignalhandler.hh"
Expand Down Expand Up @@ -82,66 +80,6 @@ bool callback( const char * dump_dir, const char * minidump_id, void * context,
#endif
#endif

QMutex logMutex;

void gdMessageHandler( QtMsgType type, const QMessageLogContext & context, const QString & mess )
{
if ( GlobalBroadcaster::instance()->getPreference() == nullptr
|| !GlobalBroadcaster::instance()->getPreference()->enableApplicationLog ) {
return;
}
QString strTime = QDateTime::currentDateTime().toString( "MM-dd hh:mm:ss" );
QString message = QString( "%1 %2\r\n" ).arg( strTime, mess );

if ( ( logFilePtr != nullptr ) && logFilePtr->isOpen() ) {
//without the lock ,on multithread,there would be assert error.
QMutexLocker _( &logMutex );
switch ( type ) {
case QtDebugMsg:
message.insert( 0, "Debug: " );
break;
case QtWarningMsg:
message.insert( 0, "Warning: " );
break;
case QtCriticalMsg:
message.insert( 0, "Critical: " );
break;
case QtFatalMsg:
message.insert( 0, "Fatal: " );
logFilePtr->write( message.toUtf8() );
logFilePtr->flush();
abort();
case QtInfoMsg:
message.insert( 0, "Info: " );
break;
}

logFilePtr->write( message.toUtf8() );
logFilePtr->flush();

return;
}

//the following code lines actually will have no chance to run, schedule to remove in the future.
QByteArray msg = mess.toUtf8().constData();
switch ( type ) {
case QtDebugMsg:
fprintf( stderr, "Debug: %s\n", msg.constData() );
break;
case QtWarningMsg:
fprintf( stderr, "Warning: %s\n", msg.constData() );
break;
case QtCriticalMsg:
fprintf( stderr, "Critical: %s\n", msg.constData() );
break;
case QtFatalMsg:
fprintf( stderr, "Fatal: %s\n", msg.constData() );
abort();
case QtInfoMsg:
fprintf( stderr, "Info: %s\n", msg.constData() );
break;
}
}

struct GDOptions
{
Expand Down Expand Up @@ -170,11 +108,6 @@ struct GDOptions
return popupGroupName;
}

inline bool needLogFile() const
{
return logFile;
}

inline bool needTranslateWord() const
{
return !word.isEmpty();
Expand Down Expand Up @@ -204,7 +137,7 @@ void processCommandLine( QCoreApplication * app, GDOptions * result )

QCommandLineOption logFileOption( QStringList() << "l"
<< "log-to-file",
QObject::tr( "Save debug messages to gd_log.txt in the config folder." ) );
QObject::tr( "Save debug messages to gd_log.txt in the config folder" ) + '.' );

QCommandLineOption resetState( QStringList() << "r"
<< "reset-window-state",
Expand Down Expand Up @@ -431,15 +364,6 @@ int main( int argc, char ** argv )
QWebEngineUrlScheme::registerScheme( webUiScheme );
}

QFile file;
logFilePtr = &file;
auto guard = qScopeGuard( [ &file ]() {
logFilePtr = nullptr;
file.close();
} );

Q_UNUSED( guard )

QFont f = QApplication::font();
f.setStyleStrategy( QFont::PreferAntialias );
QApplication::setFont( f );
Expand Down Expand Up @@ -492,9 +416,6 @@ int main( int argc, char ** argv )
for ( ;; ) {
try {
cfg = Config::load();

//enabled through command line or preference
gdcl.logFile = gdcl.logFile || cfg.preferences.enableApplicationLog;
}
catch ( Config::exError & ) {
QMessageBox mb(
Expand Down Expand Up @@ -526,13 +447,8 @@ int main( int argc, char ** argv )

cfg.resetState = gdcl.resetState;

// Open log file
logFilePtr->setFileName( Config::getConfigDir() + "gd_log.txt" );
logFilePtr->open( QFile::WriteOnly );


// Install message handler
qInstallMessageHandler( gdMessageHandler );
// Log to file enabled through command line or preference
Logger::switchLoggingMethod( gdcl.logFile || cfg.preferences.enableApplicationLog );

// Reload translations for user selected locale is nesessary
QTranslator qtTranslator;
Expand Down Expand Up @@ -630,10 +546,7 @@ int main( int argc, char ** argv )
QObject::connect( KSignalHandler::self(), &KSignalHandler::signalReceived, &m, &MainWindow::quitApp );
#endif
int r = app.exec();

if ( logFilePtr->isOpen() ) {
logFilePtr->close();
}
Logger::closeLogFile();

return r;
}
8 changes: 2 additions & 6 deletions src/termination.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,15 @@
/* This file is (c) 2008-2012 Konstantin Isakov <[email protected]>
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */

#include "logfileptr.hh"
#include "logger.hh"
#include "termination.hh"
#include <QDebug>
#include <exception>

static void termHandler()
{
qDebug() << "GoldenDict has crashed unexpectedly.\n\n";

if ( logFilePtr && logFilePtr->isOpen() ) {
logFilePtr->close();
}

Logger::closeLogFile();
abort();
}

Expand Down
3 changes: 3 additions & 0 deletions src/ui/mainwindow.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#endif

#include "mainwindow.hh"
#include "logger.hh"
#include <QWebEngineProfile>
#include "edit_dictionaries.hh"
#include "dict/loaddictionaries.hh"
Expand Down Expand Up @@ -2366,6 +2367,8 @@ void MainWindow::editPreferences()

ui.fullTextSearchAction->setEnabled( cfg.preferences.fts.enabled );

Logger::switchLoggingMethod( cfg.preferences.enableApplicationLog );

Config::save( cfg );
}

Expand Down
2 changes: 1 addition & 1 deletion src/ui/preferences.ui
Original file line number Diff line number Diff line change
Expand Up @@ -1938,7 +1938,7 @@ from Stardict, Babylon and GLS dictionaries</string>
<item>
<widget class="QCheckBox" name="enableApplicationLog">
<property name="text">
<string>Enable application log</string>
<string>Save debug messages to gd_log.txt in the config folder</string>
</property>
</widget>
</item>
Expand Down

0 comments on commit 0aedff4

Please sign in to comment.