From: Jocelyn Turcotte Date: Tue, 9 May 2017 12:24:11 +0000 (+0200) Subject: Use Qt logging categories for logging X-Git-Tag: archive/raspbian/3.16.7-1_deb13u1+rpi1~1^2~735 X-Git-Url: https://dgit.raspbian.org/?a=commitdiff_plain;h=4ad190a558c64aac846dc828438acdec5fe9c6ed;p=nextcloud-desktop.git Use Qt logging categories for logging This gives more insight about the logs and allow setting fine-tuned logging rules. The categories are set to only output Info by default so this allows us to provide more concise logging while keeping the ability to extract more information for a specific category when developping or debugging customer issues. Issue #5647 --- diff --git a/cmake/modules/Warnings.cmake b/cmake/modules/Warnings.cmake index 1ee7a9ea7..0edabd2a9 100644 --- a/cmake/modules/Warnings.cmake +++ b/cmake/modules/Warnings.cmake @@ -3,7 +3,7 @@ # For details see the accompanying COPYING* file. if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic -Wno-long-long") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic -Wno-long-long -Wno-gnu-zero-variadic-macro-arguments") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") diff --git a/src/gui/accountmanager.cpp b/src/gui/accountmanager.cpp index 84ad5d4a5..b3807c3ce 100644 --- a/src/gui/accountmanager.cpp +++ b/src/gui/accountmanager.cpp @@ -37,6 +37,8 @@ static const char serverVersionC[] = "serverVersion"; namespace OCC { +Q_LOGGING_CATEGORY(lcAccountManager, "gui.account.manager", QtInfoMsg) + AccountManager *AccountManager::instance() { static AccountManager instance; @@ -47,7 +49,7 @@ bool AccountManager::restore() { auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); if (settings->status() != QSettings::NoError) { - qDebug() << "Could not read settings from" << settings->fileName() + qCDebug(lcAccountManager) << "Could not read settings from" << settings->fileName() << settings->status(); return false; } @@ -75,7 +77,7 @@ bool AccountManager::restore() bool AccountManager::restoreFromLegacySettings() { - qDebug() << "Migrate: restoreFromLegacySettings, checking settings group" + qCDebug(lcAccountManager) << "Migrate: restoreFromLegacySettings, checking settings group" << Theme::instance()->appName(); // try to open the correctly themed settings @@ -91,7 +93,7 @@ bool AccountManager::restoreFromLegacySettings() oCCfgFile = oCCfgFile.left( oCCfgFile.lastIndexOf('/')); oCCfgFile += QLatin1String("/ownCloud/owncloud.cfg"); - qDebug() << "Migrate: checking old config " << oCCfgFile; + qCDebug(lcAccountManager) << "Migrate: checking old config " << oCCfgFile; QFileInfo fi( oCCfgFile ); if( fi.isReadable() ) { @@ -107,7 +109,7 @@ bool AccountManager::restoreFromLegacySettings() // in case the urls are equal reset the settings object to read from // the ownCloud settings object - qDebug() << "Migrate oC config if " << oCUrl << " == " << overrideUrl << ":" + qCDebug(lcAccountManager) << "Migrate oC config if " << oCUrl << " == " << overrideUrl << ":" << (oCUrl == overrideUrl ? "Yes" : "No"); if( oCUrl == overrideUrl ) { settings = std::move(oCSettings); @@ -138,31 +140,31 @@ void AccountManager::save(bool saveCredentials) } settings->sync(); - qDebug() << "Saved all account settings, status:" << settings->status(); + qCDebug(lcAccountManager) << "Saved all account settings, status:" << settings->status(); } void AccountManager::saveAccount(Account* a) { - qDebug() << "Saving account" << a->url().toString(); + qCDebug(lcAccountManager) << "Saving account" << a->url().toString(); auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); settings->beginGroup(a->id()); saveAccountHelper(a, *settings, false); // don't save credentials they might not have been loaded yet settings->endGroup(); settings->sync(); - qDebug() << "Saved account settings, status:" << settings->status(); + qCDebug(lcAccountManager) << "Saved account settings, status:" << settings->status(); } void AccountManager::saveAccountState(AccountState* a) { - qDebug() << "Saving account state" << a->account()->url().toString(); + qCDebug(lcAccountManager) << "Saving account state" << a->account()->url().toString(); auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); settings->beginGroup(a->account()->id()); a->writeToSettings(*settings); settings->endGroup(); settings->sync(); - qDebug() << "Saved account state settings, status:" << settings->status(); + qCDebug(lcAccountManager) << "Saved account state settings, status:" << settings->status(); } void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool saveCredentials) @@ -189,7 +191,7 @@ void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool s // Save accepted certificates. settings.beginGroup(QLatin1String("General")); - qDebug() << "Saving " << acc->approvedCerts().count() << " unknown certs."; + qCDebug(lcAccountManager) << "Saving " << acc->approvedCerts().count() << " unknown certs."; QByteArray certs; Q_FOREACH( const QSslCertificate& cert, acc->approvedCerts() ) { certs += cert.toPem() + '\n'; @@ -203,7 +205,7 @@ void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool s if (acc->_am) { CookieJar* jar = qobject_cast(acc->_am->cookieJar()); if (jar) { - qDebug() << "Saving cookies." << acc->cookieJarPath(); + qCDebug(lcAccountManager) << "Saving cookies." << acc->cookieJarPath(); jar->save(acc->cookieJarPath()); } } @@ -214,7 +216,7 @@ AccountPtr AccountManager::loadAccountHelper(QSettings& settings) auto urlConfig = settings.value(QLatin1String(urlC)); if (!urlConfig.isValid()) { // No URL probably means a corrupted entry in the account settings - qDebug() << "No URL for account " << settings.group(); + qCDebug(lcAccountManager) << "No URL for account " << settings.group(); return AccountPtr(); } @@ -243,7 +245,7 @@ AccountPtr AccountManager::loadAccountHelper(QSettings& settings) acc->setUrl(urlConfig.toUrl()); } - qDebug() << "Account for" << acc->url() << "using auth type" << authType; + qCDebug(lcAccountManager) << "Account for" << acc->url() << "using auth type" << authType; acc->_serverVersion = settings.value(QLatin1String(serverVersionC)).toString(); diff --git a/src/gui/accountsettings.cpp b/src/gui/accountsettings.cpp index a82dbdbf9..ec869f91d 100644 --- a/src/gui/accountsettings.cpp +++ b/src/gui/accountsettings.cpp @@ -35,7 +35,6 @@ #include -#include #include #include #include @@ -58,6 +57,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcAccountSettings, "gui.account.settings", QtInfoMsg) + static const char progressBarStyleC[] = "QProgressBar {" "border: 1px solid grey;" @@ -188,7 +189,7 @@ void AccountSettings::slotOpenAccountWizard() topLevelWidget()->close(); } #ifdef Q_OS_MAC - qDebug() << parent() << topLevelWidget(); + qCDebug(lcAccountSettings) << parent() << topLevelWidget(); SettingsDialogMac *sd = qobject_cast(topLevelWidget()); if (sd) { @@ -328,7 +329,7 @@ void AccountSettings::slotFolderWizardAccepted() FolderWizard *folderWizard = qobject_cast(sender()); FolderMan *folderMan = FolderMan::instance(); - qDebug() << "* Folder wizard completed"; + qCDebug(lcAccountSettings) << "* Folder wizard completed"; FolderDefinition definition; definition.localPath = FolderDefinition::prepareLocalPath( @@ -339,7 +340,7 @@ void AccountSettings::slotFolderWizardAccepted() { QDir dir(definition.localPath); if (!dir.exists()) { - qDebug() << "Creating folder" << definition.localPath; + qCDebug(lcAccountSettings) << "Creating folder" << definition.localPath; if (!dir.mkpath(".")) { QMessageBox::warning(this, tr("Folder creation failed"), tr("

Could not create local folder %1.") @@ -374,7 +375,7 @@ void AccountSettings::slotFolderWizardAccepted() void AccountSettings::slotFolderWizardRejected() { - qDebug() << "* Folder wizard cancelled"; + qCDebug(lcAccountSettings) << "* Folder wizard cancelled"; FolderMan *folderMan = FolderMan::instance(); folderMan->setSyncEnabled(true); } @@ -387,7 +388,7 @@ void AccountSettings::slotRemoveCurrentFolder() if( selected.isValid() && folder ) { int row = selected.row(); - qDebug() << "Remove Folder alias " << folder->alias(); + qCDebug(lcAccountSettings) << "Remove Folder alias " << folder->alias(); QString shortGuiLocalPath = folder->shortGuiLocalPath(); QMessageBox messageBox(QMessageBox::Question, @@ -444,7 +445,7 @@ void AccountSettings::showConnectionLabel( const QString& message, QStringList e } else { errors.prepend(message); const QString msg = errors.join(QLatin1String("\n")); - qDebug() << msg; + qCDebug(lcAccountSettings) << msg; ui->connectLabel->setText( msg ); ui->connectLabel->setToolTip(QString()); ui->connectLabel->setStyleSheet(errStyle); @@ -459,7 +460,7 @@ void AccountSettings::slotEnableCurrentFolder() if( !alias.isEmpty() ) { FolderMan *folderMan = FolderMan::instance(); - qDebug() << "Application: enable folder with alias " << alias; + qCDebug(lcAccountSettings) << "Application: enable folder with alias " << alias; bool terminate = false; bool currentlyPaused = false; @@ -666,7 +667,7 @@ void AccountSettings::slotLinkActivated(const QString& link) ui->_folderList->setCurrentIndex(indx); ui->_folderList->scrollTo(indx); } else { - qDebug() << "Unable to find a valid index for " << myFolder; + qCDebug(lcAccountSettings) << "Unable to find a valid index for " << myFolder; } } } diff --git a/src/gui/accountstate.cpp b/src/gui/accountstate.cpp index b92b0ae44..dae976134 100644 --- a/src/gui/accountstate.cpp +++ b/src/gui/accountstate.cpp @@ -19,12 +19,13 @@ #include "logger.h" #include "configfile.h" -#include #include #include namespace OCC { +Q_LOGGING_CATEGORY(lcAccountState, "gui.account.state", QtInfoMsg) + AccountState::AccountState(AccountPtr account) : QObject() , _account(account) @@ -85,7 +86,7 @@ AccountState::State AccountState::state() const void AccountState::setState(State state) { if (_state != state) { - qDebug() << "AccountState state change: " + qCDebug(lcAccountState) << "AccountState state change: " << stateString(_state) << "->" << stateString(state); State oldState = _state; _state = state; @@ -170,7 +171,7 @@ void AccountState::checkConnectivity() } if (_connectionValidator) { - qDebug() << "ConnectionValidator already running, ignoring" << account()->displayName(); + qCDebug(lcAccountState) << "ConnectionValidator already running, ignoring" << account()->displayName(); return; } @@ -181,7 +182,7 @@ void AccountState::checkConnectivity() if (isConnected() && _timeSinceLastETagCheck.isValid() && _timeSinceLastETagCheck.elapsed() < polltime) { - //qDebug() << account()->displayName() << "The last ETag check succeeded within the last " << polltime/1000 << " secs. No connection check needed!"; + //qCDebug(lcAccountState) << account()->displayName() << "The last ETag check succeeded within the last " << polltime/1000 << " secs. No connection check needed!"; return; } @@ -216,12 +217,12 @@ void AccountState::checkConnectivity() void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList& errors) { if (isSignedOut()) { - qDebug() << "Signed out, ignoring" << connectionStatusString(status) << _account->url().toString(); + qCDebug(lcAccountState) << "Signed out, ignoring" << connectionStatusString(status) << _account->url().toString(); return; } if (_connectionStatus != status) { - qDebug() << "AccountState connection status change: " + qCDebug(lcAccountState) << "AccountState connection status change: " << connectionStatusString(_connectionStatus) << "->" << connectionStatusString(status); _connectionStatus = status; diff --git a/src/gui/activitylistmodel.cpp b/src/gui/activitylistmodel.cpp index f794a2bf4..696e53e4e 100644 --- a/src/gui/activitylistmodel.cpp +++ b/src/gui/activitylistmodel.cpp @@ -35,6 +35,8 @@ Q_DECLARE_METATYPE(QPointer) namespace OCC { +Q_LOGGING_CATEGORY(lcActivity, "gui.activity", QtInfoMsg) + ActivityListModel::ActivityListModel(QWidget *parent) :QAbstractListModel(parent) { @@ -138,7 +140,7 @@ void ActivityListModel::startFetchJob(AccountState* s) job->addQueryParams(params); _currentlyFetching.insert(s); - qDebug() << Q_FUNC_INFO << "Start fetching activities for " << s->account()->displayName(); + qCDebug(lcActivity) << "Start fetching activities for " << s->account()->displayName(); job->start(); } diff --git a/src/gui/activitylistmodel.h b/src/gui/activitylistmodel.h index f0f6adda4..ed3a9e270 100644 --- a/src/gui/activitylistmodel.h +++ b/src/gui/activitylistmodel.h @@ -23,6 +23,8 @@ class QJsonDocument; namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcActivity) + class AccountState; /** diff --git a/src/gui/activitywidget.cpp b/src/gui/activitywidget.cpp index bcaaa3f70..5be315f4c 100644 --- a/src/gui/activitywidget.cpp +++ b/src/gui/activitywidget.cpp @@ -50,8 +50,6 @@ namespace OCC { -/* ==================================================================== */ - ActivityWidget::ActivityWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::ActivityWidget), @@ -122,7 +120,7 @@ void ActivityWidget::slotRefreshNotifications(AccountState *ptr) snh->slotFetchNotifications(ptr); } else { - qDebug() << Q_FUNC_INFO << "========> notification request counter not zero."; + qCDebug(lcActivity) << "========> notification request counter not zero."; } } @@ -230,7 +228,7 @@ void ActivityWidget::checkActivityTabVisibility() void ActivityWidget::slotOpenFile(QModelIndex indx) { - qDebug() << Q_FUNC_INFO << indx.isValid() << indx.data(ActivityItemDelegate::PathRole).toString() << QFile::exists(indx.data(ActivityItemDelegate::PathRole).toString()); + qCDebug(lcActivity) << indx.isValid() << indx.data(ActivityItemDelegate::PathRole).toString() << QFile::exists(indx.data(ActivityItemDelegate::PathRole).toString()); if( indx.isValid() ) { QString fullPath = indx.data(ActivityItemDelegate::PathRole).toString(); @@ -254,7 +252,7 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) foreach( auto activity, list ) { if( _blacklistedNotifications.contains(activity)) { - qDebug() << Q_FUNC_INFO << "Activity in blacklist, skip"; + qCDebug(lcActivity) << "Activity in blacklist, skip"; continue; } @@ -378,7 +376,7 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) void ActivityWidget::slotSendNotificationRequest(const QString& accountName, const QString& link, const QByteArray& verb) { - qDebug() << Q_FUNC_INFO << "Server Notification Request " << verb << link << "on account" << accountName; + qCDebug(lcActivity) << "Server Notification Request " << verb << link << "on account" << accountName; NotificationWidget *theSender = qobject_cast(sender()); const QStringList validVerbs = QStringList() << "GET" << "PUT" << "POST" << "DELETE"; @@ -401,7 +399,7 @@ void ActivityWidget::slotSendNotificationRequest(const QString& accountName, con _notificationRequestsRunning++; } } else { - qDebug() << Q_FUNC_INFO << "Notification Links: Invalid verb:" << verb; + qCDebug(lcActivity) << "Notification Links: Invalid verb:" << verb; } } @@ -423,7 +421,7 @@ void ActivityWidget::slotNotifyNetworkError( QNetworkReply *reply) int resultCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); endNotificationRequest(job->widget(), resultCode); - qDebug() << Q_FUNC_INFO << "Server notify job failed with code " << resultCode; + qCDebug(lcActivity) << "Server notify job failed with code " << resultCode; } @@ -436,7 +434,7 @@ void ActivityWidget::slotNotifyServerFinished( const QString& reply, int replyCo endNotificationRequest(job->widget(), replyCode); // FIXME: remove the widget after a couple of seconds - qDebug() << Q_FUNC_INFO << "Server Notification reply code"<< replyCode << reply; + qCDebug(lcActivity) << "Server Notification reply code"<< replyCode << reply; // if the notification was successful start a timer that triggers // removal of the done widgets in a few seconds @@ -563,7 +561,7 @@ ActivitySettings::ActivitySettings(QWidget *parent) void ActivitySettings::setNotificationRefreshInterval( quint64 interval ) { - qDebug() << "Starting Notification refresh timer with " << interval/1000 << " sec interval"; + qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval/1000 << " sec interval"; _notificationCheckTimer.start(interval); } @@ -637,7 +635,7 @@ void ActivitySettings::slotRefresh( AccountState* ptr ) // Fetch Activities only if visible and if last check is longer than 15 secs ago if( timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD ) { - qDebug() << Q_FUNC_INFO << "do not check as last check is only secs ago: " << timer.elapsed() / 1000; + qCDebug(lcActivity) << "do not check as last check is only secs ago: " << timer.elapsed() / 1000; return; } if( ptr && ptr->isConnected() ) { diff --git a/src/gui/application.cpp b/src/gui/application.cpp index 862fd8c1e..aac0666cf 100644 --- a/src/gui/application.cpp +++ b/src/gui/application.cpp @@ -59,6 +59,8 @@ class QSocket; namespace OCC { +Q_LOGGING_CATEGORY(lcApplication, "gui.application", QtInfoMsg) + namespace { static const char optionsC[] = @@ -79,7 +81,7 @@ QString applicationTrPath() QString devTrPath = qApp->applicationDirPath() + QString::fromLatin1("/../src/gui/"); if (QDir(devTrPath).exists()) { // might miss Qt, QtKeyChain, etc. - qDebug() << "Running from build location! Translations may be incomplete!"; + qCDebug(lcApplication) << "Running from build location! Translations may be incomplete!"; return devTrPath; } #if defined(Q_OS_WIN) @@ -148,7 +150,7 @@ Application::Application(int &argc, char **argv) : setupTranslations(); // Setup global excludes - qDebug() << "Loading global exclude list"; + qCDebug(lcApplication) << "Loading global exclude list"; ConfigFile cfg; ExcludedFiles& excludes = ExcludedFiles::instance(); excludes.addExcludeFilePath( cfg.excludeFile(ConfigFile::SystemScope) ); @@ -165,7 +167,7 @@ Application::Application(int &argc, char **argv) : // (non-existence is not an error) Utility::sleep(5); if (!AccountManager::instance()->restore()) { - qDebug() << "Could not read the account settings, quitting"; + qCDebug(lcApplication) << "Could not read the account settings, quitting"; QMessageBox::critical( 0, tr("Error accessing the configuration file"), @@ -292,7 +294,6 @@ void Application::slotCleanup() void Application::slotSystemOnlineConfigurationChanged(QNetworkConfiguration cnf) { if (cnf.state() & QNetworkConfiguration::Active) { - //qDebug() << "Trying fast reconnect"; QMetaObject::invokeMethod(this, "slotCheckConnection", Qt::QueuedConnection); } } @@ -360,7 +361,7 @@ void Application::setupLogging() Logger::instance()->enterNextLogFile(); - qDebug() << QString::fromLatin1( "################## %1 %2 (%3) %4 on %5").arg(_theme->appName()) + qCDebug(lcApplication) << QString::fromLatin1( "################## %1 %2 (%3) %4 on %5").arg(_theme->appName()) .arg( QLocale::system().name() ) .arg(property("ui_lang").toString()) .arg(_theme->version()) @@ -380,10 +381,10 @@ void Application::slotParseMessage(const QString &msg, QObject*) parseOptions(options); setupLogging(); } else if (msg.startsWith(QLatin1String("MSG_SHOWSETTINGS"))) { - qDebug() << "Running for" << _startedAt.elapsed()/1000.0 << "sec"; + qCDebug(lcApplication) << "Running for" << _startedAt.elapsed()/1000.0 << "sec"; if (_startedAt.elapsed() < 10*1000) { // This call is mirrored with the one in int main() - qWarning() << "Ignoring MSG_SHOWSETTINGS, possibly double-invocation of client via session restore and auto start"; + qCWarning(lcApplication) << "Ignoring MSG_SHOWSETTINGS, possibly double-invocation of client via session restore and auto start"; return; } showSettingsDialog(); @@ -570,7 +571,7 @@ void Application::setupTranslations() // for us to accept the language. Otherwise, we try with the next. // "en" is an exception as it is the default language and may not // have a translation file provided. - qDebug() << Q_FUNC_INFO << "Using" << lang << "translation"; + qCDebug(lcApplication) << "Using" << lang << "translation"; setProperty("ui_lang", lang); const QString qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath); const QString qtTrFile = QLatin1String("qt_") + lang; diff --git a/src/gui/application.h b/src/gui/application.h index 0dec628fe..b7166c56a 100644 --- a/src/gui/application.h +++ b/src/gui/application.h @@ -41,6 +41,9 @@ class Handler; } namespace OCC { + +Q_DECLARE_LOGGING_CATEGORY(lcApplication) + class Theme; class Folder; class SslErrorDialog; diff --git a/src/gui/clipboard.mm b/src/gui/clipboard.mm index 56361b7c9..48ea81387 100644 --- a/src/gui/clipboard.mm +++ b/src/gui/clipboard.mm @@ -1,5 +1,4 @@ #include -#include #import namespace OCC { @@ -7,7 +6,6 @@ namespace OCC { // https://github.com/owncloud/client/issues/3300 void copyToPasteboard(const QString &string) { - qDebug() << Q_FUNC_INFO << string; [[NSPasteboard generalPasteboard] clearContents]; [[NSPasteboard generalPasteboard] setString:[NSString stringWithUTF8String:string.toUtf8().data()] forType:NSStringPboardType]; diff --git a/src/gui/creds/credentialsfactory.cpp b/src/gui/creds/credentialsfactory.cpp index 590fc716f..9a60209c7 100644 --- a/src/gui/creds/credentialsfactory.cpp +++ b/src/gui/creds/credentialsfactory.cpp @@ -12,6 +12,7 @@ * for more details. */ +#include #include #include "creds/credentialsfactory.h" @@ -24,6 +25,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcGuiCredentials, "gui.credentials", QtInfoMsg) + namespace CredentialsFactory { @@ -39,7 +42,7 @@ AbstractCredentials* create(const QString& type) return new ShibbolethCredentials; #endif } else { - qWarning("Unknown credentials type: %s", qPrintable(type)); + qCWarning(lcGuiCredentials, "Unknown credentials type: %s", qPrintable(type)); return new DummyCredentials; } } diff --git a/src/gui/creds/shibboleth/shibbolethuserjob.cpp b/src/gui/creds/shibboleth/shibbolethuserjob.cpp index e53d78294..02d4d22f4 100644 --- a/src/gui/creds/shibboleth/shibbolethuserjob.cpp +++ b/src/gui/creds/shibboleth/shibbolethuserjob.cpp @@ -17,9 +17,12 @@ #include #include +#include namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcShibboleth) + ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject* parent) : JsonApiJob(account, QLatin1String("ocs/v1.php/cloud/user"), parent) { @@ -30,10 +33,9 @@ ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject* parent) void ShibbolethUserJob::slotJsonReceived(const QJsonDocument &json, int statusCode) { if( statusCode != 100 ) { - qWarning() << "JSON Api call resulted in status code != 100"; + qCWarning(lcShibboleth) << "JSON Api call resulted in status code != 100"; } QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString(); - //qDebug() << "cloud/user: " << json << "->" << user; emit userFetched(user); } diff --git a/src/gui/creds/shibboleth/shibbolethwebview.cpp b/src/gui/creds/shibboleth/shibbolethwebview.cpp index 1504d6c52..ccc9a96a5 100644 --- a/src/gui/creds/shibboleth/shibbolethwebview.cpp +++ b/src/gui/creds/shibboleth/shibbolethwebview.cpp @@ -13,7 +13,6 @@ */ #include -#include #include #include #include @@ -156,7 +155,7 @@ void ShibbolethWebView::slotLoadFinished(bool success) } if (!success) { - qDebug() << Q_FUNC_INFO << "Could not load Shibboleth login page to log you in."; + qCDebug(lcShibboleth) << "Could not load Shibboleth login page to log you in."; } } diff --git a/src/gui/creds/shibbolethcredentials.cpp b/src/gui/creds/shibbolethcredentials.cpp index 664294b2e..f34ed9aae 100644 --- a/src/gui/creds/shibbolethcredentials.cpp +++ b/src/gui/creds/shibbolethcredentials.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include "creds/shibbolethcredentials.h" #include "creds/shibboleth/shibbolethwebview.h" @@ -39,6 +38,8 @@ using namespace QKeychain; namespace OCC { +Q_LOGGING_CATEGORY(lcShibboleth, "gui.credentials.shibboleth", QtInfoMsg) + namespace { @@ -107,7 +108,7 @@ void ShibbolethCredentials::slotReplyFinished(QNetworkReply* r) QVariant target = r->attribute(QNetworkRequest::RedirectionTargetAttribute); if (target.isValid()) { _stillValid = false; - qWarning() << Q_FUNC_INFO << "detected redirect, will open Login Window"; // will be done in NetworkJob's finished signal + qCWarning(lcShibboleth) << "detected redirect, will open Login Window"; // will be done in NetworkJob's finished signal } else { //_stillValid = true; // gets set when reading from keychain or getting it from browser } @@ -213,11 +214,11 @@ void ShibbolethCredentials::slotUserFetched(const QString &user) { if (_user.isEmpty()) { if (user.isEmpty()) { - qDebug() << "Failed to fetch the shibboleth user"; + qCDebug(lcShibboleth) << "Failed to fetch the shibboleth user"; } _user = user; } else if (user != _user) { - qDebug() << "Wrong user: " << user << "!=" << _user; + qCDebug(lcShibboleth) << "Wrong user: " << user << "!=" << _user; QMessageBox::warning(_browser, tr("Login Error"), tr("You must sign in as user %1").arg(_user)); invalidateToken(); showLoginWindow(); diff --git a/src/gui/creds/shibbolethcredentials.h b/src/gui/creds/shibbolethcredentials.h index 7c9b8135c..1114b4d6c 100644 --- a/src/gui/creds/shibbolethcredentials.h +++ b/src/gui/creds/shibbolethcredentials.h @@ -16,6 +16,7 @@ #define MIRALL_CREDS_SHIBBOLETH_CREDENTIALS_H #include +#include #include #include #include @@ -32,6 +33,8 @@ class QAuthenticator; namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcShibboleth) + class ShibbolethWebView; /** diff --git a/src/gui/folder.cpp b/src/gui/folder.cpp index 02abe1da5..c132d60e9 100644 --- a/src/gui/folder.cpp +++ b/src/gui/folder.cpp @@ -35,7 +35,6 @@ #include "creds/abstractcredentials.h" -#include #include #include #include @@ -46,6 +45,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcFolder, "gui.folder", QtInfoMsg) + Folder::Folder(const FolderDefinition& definition, AccountState* accountState, QObject* parent) @@ -81,7 +82,7 @@ Folder::Folder(const FolderDefinition& definition, _engine->setIgnoreHiddenFiles(_definition.ignoreHiddenFiles); if (!setIgnoredFiles()) - qWarning("Could not read system exclude file"); + qCWarning(lcFolder, "Could not read system exclude file"); connect(_accountState.data(), SIGNAL(isConnectedChanged()), this, SIGNAL(canSyncChanged())); connect(_engine.data(), SIGNAL(rootEtag(QString)), this, SLOT(etagRetreivedFromSyncEngine(QString))); @@ -124,14 +125,14 @@ void Folder::checkLocalPath() const QFileInfo fi(_definition.localPath); _canonicalLocalPath = fi.canonicalFilePath(); if (_canonicalLocalPath.isEmpty()) { - qDebug() << "Broken symlink:" << _definition.localPath; + qCDebug(lcFolder) << "Broken symlink:" << _definition.localPath; _canonicalLocalPath = _definition.localPath; } else if( !_canonicalLocalPath.endsWith('/') ) { _canonicalLocalPath.append('/'); } if( fi.isDir() && fi.isReadable() ) { - qDebug() << "Checked local path ok"; + qCDebug(lcFolder) << "Checked local path ok"; } else { // Check directory again if( !FileSystem::fileExists(_definition.localPath, fi) ) { @@ -270,17 +271,17 @@ void Folder::prepareToSync() void Folder::slotRunEtagJob() { - qDebug() << "* Trying to check" << remoteUrl().toString() << "for changes via ETag check. (time since last sync:" << (_timeSinceLastSyncDone.elapsed() / 1000) << "s)"; + qCDebug(lcFolder) << "Trying to check" << remoteUrl().toString() << "for changes via ETag check. (time since last sync:" << (_timeSinceLastSyncDone.elapsed() / 1000) << "s)"; AccountPtr account = _accountState->account(); if (_requestEtagJob) { - qDebug() << Q_FUNC_INFO << remoteUrl().toString() << "has ETag job queued, not trying to sync"; + qCDebug(lcFolder) << remoteUrl().toString() << "has ETag job queued, not trying to sync"; return; } if (!canSync()) { - qDebug() << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state()); + qCDebug(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state()); return; } @@ -297,13 +298,11 @@ void Folder::slotRunEtagJob() void Folder::etagRetreived(const QString& etag) { - //qDebug() << "* Compare etag with previous etag: last:" << _lastEtag << ", received:" << etag; - // re-enable sync if it was disabled because network was down FolderMan::instance()->setSyncEnabled(true); if (_lastEtag != etag) { - qDebug() << "* Compare etag with previous etag: last:" << _lastEtag << ", received:" << etag << "-> CHANGED"; + qCDebug(lcFolder) << "Compare etag with previous etag: last:" << _lastEtag << ", received:" << etag << "-> CHANGED"; _lastEtag = etag; slotScheduleThisFolder(); } @@ -313,7 +312,7 @@ void Folder::etagRetreived(const QString& etag) void Folder::etagRetreivedFromSyncEngine(const QString& etag) { - qDebug() << "Root etag from during sync:" << etag; + qCDebug(lcFolder) << "Root etag from during sync:" << etag; accountState()->tagLastSuccessfullETagRequest(); _lastEtag = etag; } @@ -349,7 +348,7 @@ void Folder::showSyncResultPopup() createGuiLog( _syncResult.firstItemError()->_file, LogStatusError, errorCount ); } - qDebug() << "OO folder slotSyncFinished: result: " << int(_syncResult.status()); + qCDebug(lcFolder) << "Folder slotSyncFinished: result: " << int(_syncResult.status()); } void Folder::createGuiLog( const QString& filename, LogStatus status, int count, @@ -428,7 +427,7 @@ int Folder::slotDiscardDownloadProgress() _journal.getAndDeleteStaleDownloadInfos(keep_nothing); foreach (const SyncJournalDb::DownloadInfo & deleted_info, deleted_infos) { const QString tmppath = folderpath.filePath(deleted_info._tmpfile); - qDebug() << "Deleting temporary file: " << tmppath; + qCDebug(lcFolder) << "Deleting temporary file: " << tmppath; FileSystem::remove(tmppath); } return deleted_infos.size(); @@ -474,7 +473,7 @@ void Folder::slotWatchedPathChanged(const QString& path) auto record = _journal.getFileRecord(relativePath); if (record.isValid() && !FileSystem::fileChanged(path, record._fileSize, Utility::qDateTimeToTime_t(record._modtime))) { - qDebug() << "Ignoring spurious notification for file" << relativePath; + qCDebug(lcFolder) << "Ignoring spurious notification for file" << relativePath; return; // probably a spurious notification } } @@ -518,7 +517,7 @@ void Folder::saveToSettings() const FolderDefinition::save(*settings, _definition); settings->sync(); - qDebug() << "Saved folder" << _definition.alias << "to settings, status" << settings->status(); + qCDebug(lcFolder) << "Saved folder" << _definition.alias << "to settings, status" << settings->status(); } void Folder::removeFromSettings() const @@ -543,7 +542,7 @@ bool Folder::isFileExcludedRelative(const QString& relativePath) const void Folder::slotTerminateSync() { - qDebug() << "folder " << alias() << " Terminating!"; + qCDebug(lcFolder) << "folder " << alias() << " Terminating!"; if( _engine->isSyncRunning() ) { _engine->abort(); @@ -569,12 +568,12 @@ void Folder::wipe() QFile file(stateDbFile); if( file.exists() ) { if( !file.remove()) { - qDebug() << "WRN: Failed to remove existing csync StateDB " << stateDbFile; + qCDebug(lcFolder) << "WRN: Failed to remove existing csync StateDB " << stateDbFile; } else { - qDebug() << "wipe: Removed csync StateDB " << stateDbFile; + qCDebug(lcFolder) << "wipe: Removed csync StateDB " << stateDbFile; } } else { - qDebug() << "WRN: statedb is empty, can not remove."; + qCDebug(lcFolder) << "WRN: statedb is empty, can not remove."; } // Also remove other db related files @@ -595,12 +594,12 @@ bool Folder::setIgnoredFiles() // a QSet of files to load. ConfigFile cfg; QString systemList = cfg.excludeFile(ConfigFile::SystemScope); - qDebug() << "==== adding system ignore list to csync:" << systemList; + qCDebug(lcFolder) << "Adding system ignore list to csync:" << systemList; _engine->excludedFiles().addExcludeFilePath(systemList); QString userList = cfg.excludeFile(ConfigFile::UserScope); if( QFile::exists(userList) ) { - qDebug() << "==== adding user defined ignore list to csync:" << userList; + qCDebug(lcFolder) << "Adding user defined ignore list to csync:" << userList; _engine->excludedFiles().addExcludeFilePath(userList); } @@ -625,7 +624,7 @@ void Folder::startSync(const QStringList &pathList) } if (isBusy()) { - qCritical() << "* ERROR csync is still running and new sync requested."; + qCCritical(lcFolder) << "ERROR csync is still running and new sync requested."; return; } _csyncUnavail = false; @@ -634,7 +633,7 @@ void Folder::startSync(const QStringList &pathList) _syncResult.setStatus( SyncResult::SyncPrepare ); emit syncStateChange(); - qDebug() << "*** Start syncing " << remoteUrl().toString() << " - client version" + qCDebug(lcFolder) << "*** Start syncing " << remoteUrl().toString() << " - client version" << qPrintable(Theme::instance()->version()); _fileLog->start(path()); @@ -731,7 +730,7 @@ void Folder::slotSyncError(const QString& err) void Folder::slotSyncStarted() { - qDebug() << "#### Propagation start #################################################### >>"; + qCDebug(lcFolder) << "#### Propagation start #################################################### >>"; _syncResult.setStatus(SyncResult::SyncRunning); emit syncStateChange(); } @@ -743,7 +742,7 @@ void Folder::slotCsyncUnavailable() void Folder::slotSyncFinished(bool success) { - qDebug() << " - client version" << qPrintable(Theme::instance()->version()) + qCDebug(lcFolder) << "Client version" << qPrintable(Theme::instance()->version()) << " Qt" << qVersion() #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) << " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data() @@ -752,9 +751,9 @@ void Folder::slotSyncFinished(bool success) bool syncError = !_syncResult.errorStrings().isEmpty(); if( syncError ) { - qDebug() << "-> SyncEngine finished with ERROR"; + qCDebug(lcFolder) << "SyncEngine finished with ERROR"; } else { - qDebug() << "-> SyncEngine finished without problem."; + qCDebug(lcFolder) << "SyncEngine finished without problem."; } _fileLog->finish(); showSyncResultPopup(); @@ -763,10 +762,10 @@ void Folder::slotSyncFinished(bool success) if (syncError) { _syncResult.setStatus(SyncResult::Error); - qDebug() << " * owncloud csync thread finished with error"; + qCDebug(lcFolder) << "ownCloud csync thread finished with error"; } else if (_csyncUnavail) { _syncResult.setStatus(SyncResult::Error); - qDebug() << " ** csync not available."; + qCDebug(lcFolder) << "csync not available."; } else if( _syncResult.foundFilesNotSynced() ) { _syncResult.setStatus(SyncResult::Problem); } else if( _definition.paused ) { @@ -785,7 +784,7 @@ void Folder::slotSyncFinished(bool success) else { _consecutiveFailingSyncs++; - qDebug() << "the last" << _consecutiveFailingSyncs << "syncs failed"; + qCDebug(lcFolder) << "the last" << _consecutiveFailingSyncs << "syncs failed"; } if (_syncResult.status() == SyncResult::Success && success) { @@ -809,7 +808,7 @@ void Folder::slotSyncFinished(bool success) // Increment the follow-up sync counter if necessary. if (anotherSyncNeeded == ImmediateFollowUp) { _consecutiveFollowUpSyncs++; - qDebug() << "another sync was requested by the finished sync, this has" + qCDebug(lcFolder) << "another sync was requested by the finished sync, this has" << "happened" << _consecutiveFollowUpSyncs << "times"; } else { _consecutiveFollowUpSyncs = 0; diff --git a/src/gui/folderman.cpp b/src/gui/folderman.cpp index 6e4122c4e..03b32581a 100644 --- a/src/gui/folderman.cpp +++ b/src/gui/folderman.cpp @@ -40,6 +40,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcFolderMan, "gui.folder.manager", QtInfoMsg) + FolderMan* FolderMan::_instance = 0; FolderMan::FolderMan(QObject *parent) : @@ -56,7 +58,7 @@ FolderMan::FolderMan(QObject *parent) : ConfigFile cfg; int polltime = cfg.remotePollInterval(); - qDebug() << "setting remote poll timer interval to" << polltime << "msec"; + qCDebug(lcFolderMan) << "setting remote poll timer interval to" << polltime << "msec"; _etagPollTimer.setInterval( polltime ); QObject::connect(&_etagPollTimer, SIGNAL(timeout()), this, SLOT(slotEtagPollTimerTimeout())); _etagPollTimer.start(); @@ -204,7 +206,7 @@ int FolderMan::setupFolders() return r; } - qDebug() << "* Setup folders from settings file"; + qCDebug(lcFolderMan) << "* Setup folders from settings file"; foreach (const auto& account, AccountManager::instance()->accounts()) { const auto id = account->account()->id(); @@ -264,7 +266,7 @@ int FolderMan::setupFoldersMigration() QDir storageDir(cfg.configPath()); _folderConfigPath = cfg.configPath() + QLatin1String("folders"); - qDebug() << "* Setup folders from " << _folderConfigPath << "(migration)"; + qCDebug(lcFolderMan) << "* Setup folders from " << _folderConfigPath << "(migration)"; QDir dir( _folderConfigPath ); //We need to include hidden files just in case the alias starts with '.' @@ -291,7 +293,7 @@ bool FolderMan::ensureJournalGone( const QString& journalDbFile ) { // remove the old journal file while (QFile::exists(journalDbFile) && !QFile::remove(journalDbFile)) { - qDebug() << "Could not remove old db file at" << journalDbFile; + qCDebug(lcFolderMan) << "Could not remove old db file at" << journalDbFile; int ret = QMessageBox::warning(0, tr("Could not reset folder state"), tr("An old sync journal '%1' was found, " "but could not be removed. Please make sure " @@ -369,7 +371,7 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat { Folder *folder = 0; - qDebug() << " ` -> setting up:" << file; + qCDebug(lcFolderMan) << " ` -> setting up:" << file; QString escapedAlias(file); // check the unescaped variant (for the case when the filename comes out // of the directory listing). If the file does not exist, escape the @@ -382,12 +384,12 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat cfgFile.setFile( _folderConfigPath, escapedAlias ); } if( !cfgFile.isReadable() ) { - qDebug() << "Cannot read folder definition for alias " << cfgFile.filePath(); + qCDebug(lcFolderMan) << "Cannot read folder definition for alias " << cfgFile.filePath(); return folder; } QSettings settings( _folderConfigPath + QLatin1Char('/') + escapedAlias, QSettings::IniFormat); - qDebug() << " -> file path: " << settings.fileName(); + qCDebug(lcFolderMan) << " -> file path: " << settings.fileName(); // Check if the filename is equal to the group setting. If not, use the group // name as an alias. @@ -407,7 +409,7 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat QString alias = unescapeAlias( escapedAlias ); if (backend.isEmpty() || backend != QLatin1String("owncloud")) { - qWarning() << "obsolete configuration of type" << backend; + qCWarning(lcFolderMan) << "obsolete configuration of type" << backend; return 0; } @@ -417,7 +419,7 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat } if (!accountState) { - qWarning() << "can't create folder without an account"; + qCWarning(lcFolderMan) << "can't create folder without an account"; return 0; } @@ -441,7 +443,7 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat folder->saveToSettings(); } - qDebug() << "Migrated!" << folder; + qCDebug(lcFolderMan) << "Migrated!" << folder; settings.sync(); return folder; } @@ -449,7 +451,7 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat void FolderMan::slotFolderSyncPaused( Folder *f, bool paused ) { if( !f ) { - qWarning() << "!! slotFolderSyncPaused called with empty folder"; + qCWarning(lcFolderMan) << "!! slotFolderSyncPaused called with empty folder"; return; } @@ -507,7 +509,7 @@ void FolderMan::scheduleAllFolders() void FolderMan::slotScheduleAppRestart() { _appRestartRequired = true; - qDebug() << "## Application restart requested!"; + qCDebug(lcFolderMan) << "## Application restart requested!"; } void FolderMan::slotSyncOnceFileUnlocks(const QString& path) @@ -522,16 +524,16 @@ void FolderMan::slotSyncOnceFileUnlocks(const QString& path) void FolderMan::scheduleFolder( Folder *f ) { if( !f ) { - qWarning() << "slotScheduleSync called with null folder"; + qCWarning(lcFolderMan) << "slotScheduleSync called with null folder"; return; } auto alias = f->alias(); - qDebug() << "Schedule folder " << alias << " to sync!"; + qCDebug(lcFolderMan) << "Schedule folder " << alias << " to sync!"; if( ! _scheduledFolders.contains(f) ) { if( !f->canSync() ) { - qDebug() << "Folder is not ready to sync, not scheduled!"; + qCDebug(lcFolderMan) << "Folder is not ready to sync, not scheduled!"; _socketApi->slotUpdateFolderView(f); return; } @@ -540,7 +542,7 @@ void FolderMan::scheduleFolder( Folder *f ) _scheduledFolders.enqueue(f); emit scheduleQueueChanged(); } else { - qDebug() << " II> Sync for folder " << alias << " already scheduled, do not enqueue!"; + qCDebug(lcFolderMan) << " II> Sync for folder " << alias << " already scheduled, do not enqueue!"; } startScheduledSyncSoon(); @@ -549,10 +551,10 @@ void FolderMan::scheduleFolder( Folder *f ) void FolderMan::scheduleFolderNext(Folder* f) { auto alias = f->alias(); - qDebug() << "Schedule folder " << alias << " to sync! Front-of-queue."; + qCDebug(lcFolderMan) << "Schedule folder " << alias << " to sync! Front-of-queue."; if( !f->canSync() ) { - qDebug() << "Folder is not ready to sync, not scheduled!"; + qCDebug(lcFolderMan) << "Folder is not ready to sync, not scheduled!"; return; } @@ -593,14 +595,14 @@ void FolderMan::slotRunOneEtagJob() } } if (_currentEtagJob.isNull()) { - //qDebug() << "No more remote ETag check jobs to schedule."; + //qCDebug(lcFolderMan) << "No more remote ETag check jobs to schedule."; /* now it might be a good time to check for restarting... */ if( _currentSyncFolder == NULL && _appRestartRequired ) { restartApplication(); } } else { - qDebug() << "Scheduling" << folder->remoteUrl().toString() << "to check remote ETag"; + qCDebug(lcFolderMan) << "Scheduling" << folder->remoteUrl().toString() << "to check remote ETag"; _currentEtagJob->start(); // on destroy/end it will continue the queue via slotEtagJobDestroyed } } @@ -615,7 +617,7 @@ void FolderMan::slotAccountStateChanged() QString accountName = accountState->account()->displayName(); if (accountState->isConnected()) { - qDebug() << "Account" << accountName << "connected, scheduling its folders"; + qCDebug(lcFolderMan) << "Account" << accountName << "connected, scheduling its folders"; foreach (Folder *f, _folderMap.values()) { if (f @@ -625,7 +627,7 @@ void FolderMan::slotAccountStateChanged() } } } else { - qDebug() << "Account" << accountName << "disconnected or paused, " + qCDebug(lcFolderMan) << "Account" << accountName << "disconnected or paused, " "terminating or descheduling sync folders"; if (_currentSyncFolder @@ -692,7 +694,7 @@ void FolderMan::startScheduledSyncSoon() // Time since the last sync run counts against the delay msDelay = qMax(1ll, msDelay - msSinceLastSync); - qDebug() << "Starting the next scheduled sync in" << (msDelay/1000) << "seconds"; + qCDebug(lcFolderMan) << "Starting the next scheduled sync in" << (msDelay/1000) << "seconds"; _startScheduledSyncTimer.start(msDelay); } @@ -704,16 +706,16 @@ void FolderMan::startScheduledSyncSoon() void FolderMan::slotStartScheduledFolderSync() { if( _currentSyncFolder ) { - qDebug() << "Currently folder " << _currentSyncFolder->remoteUrl().toString() << " is running, wait for finish!"; + qCDebug(lcFolderMan) << "Currently folder " << _currentSyncFolder->remoteUrl().toString() << " is running, wait for finish!"; return; } if( ! _syncEnabled ) { - qDebug() << "FolderMan: Syncing is disabled, no scheduling."; + qCDebug(lcFolderMan) << "FolderMan: Syncing is disabled, no scheduling."; return; } - qDebug() << "XX slotScheduleFolderSync: folderQueue size: " << _scheduledFolders.count(); + qCDebug(lcFolderMan) << "XX slotScheduleFolderSync: folderQueue size: " << _scheduledFolders.count(); if( _scheduledFolders.isEmpty() ) { return; } @@ -743,7 +745,6 @@ void FolderMan::slotStartScheduledFolderSync() void FolderMan::slotEtagPollTimerTimeout() { - //qDebug() << Q_FUNC_INFO << "Checking if we need to make any folders check the remote ETag"; ConfigFile cfg; int polltime = cfg.remotePollInterval(); @@ -798,7 +799,7 @@ void FolderMan::slotServerVersionChanged(Account *account) { // Pause folders if the server version is unsupported if (account->serverVersionUnsupported()) { - qDebug() << "The server version is unsupported:" << account->serverVersion() + qCDebug(lcFolderMan) << "The server version is unsupported:" << account->serverVersion() << "pausing all folders on the account"; foreach (auto& f, _folderMap) { @@ -831,7 +832,7 @@ void FolderMan::slotScheduleFolderByTime() bool forceSyncIntervalExpired = quint64(msecsSinceSync) > ConfigFile().forceSyncInterval(); if (forceSyncIntervalExpired) { - qDebug() << "** scheduling folder" << f->alias() + qCDebug(lcFolderMan) << "** scheduling folder" << f->alias() << "because it has been" << msecsSinceSync << "ms " << "since the last sync"; @@ -848,7 +849,7 @@ void FolderMan::slotScheduleFolderByTime() syncAgainDelay = 60 * 1000; // 60s for each further attempt if (syncAgain && msecsSinceSync > syncAgainDelay) { - qDebug() << "** scheduling folder" << f->alias() + qCDebug(lcFolderMan) << "** scheduling folder" << f->alias() << ", the last" << f->consecutiveFailingSyncs() << "syncs failed" << ", anotherSyncNeeded" << f->syncEngine().isAnotherSyncNeeded() << ", last status:" << f->syncResult().statusString() @@ -864,7 +865,7 @@ void FolderMan::slotScheduleFolderByTime() void FolderMan::slotFolderSyncStarted( ) { - qDebug() << ">===================================== sync started for " << _currentSyncFolder->remoteUrl().toString(); + qCDebug(lcFolderMan) << ">===================================== sync started for " << _currentSyncFolder->remoteUrl().toString(); } /* @@ -875,7 +876,7 @@ void FolderMan::slotFolderSyncStarted( ) */ void FolderMan::slotFolderSyncFinished( const SyncResult& ) { - qDebug() << "<===================================== sync finished for " << _currentSyncFolder->remoteUrl().toString(); + qCDebug(lcFolderMan) << "<===================================== sync finished for " << _currentSyncFolder->remoteUrl().toString(); _lastSyncFolder = _currentSyncFolder; _currentSyncFolder = 0; @@ -926,7 +927,7 @@ Folder* FolderMan::addFolderInternal(FolderDefinition folderDefinition, auto folder = new Folder(folderDefinition, accountState, this ); - qDebug() << "Adding folder to Folder Map " << folder << folder->alias(); + qCDebug(lcFolderMan) << "Adding folder to Folder Map " << folder << folder->alias(); _folderMap[folder->alias()] = folder; if (folder->syncPaused()) { _disabledFolders.insert(folder); @@ -956,7 +957,6 @@ Folder *FolderMan::folderForPath(const QString &path) if(absolutePath.startsWith(folderPath, (Utility::isWindows() || Utility::isMac())? Qt::CaseInsensitive : Qt::CaseSensitive)) { - //qDebug() << "found folder: " << folder->path() << " for " << absolutePath; return folder; } } @@ -988,11 +988,11 @@ QStringList FolderMan::findFileInLocalFolders( const QString& relPath, const Acc void FolderMan::removeFolder( Folder *f ) { if( !f ) { - qWarning() << "!! Can not remove null folder"; + qCWarning(lcFolderMan) << "!! Can not remove null folder"; return; } - qDebug() << "Removing " << f->alias(); + qCDebug(lcFolderMan) << "Removing " << f->alias(); const bool currentlyRunning = (_currentSyncFolder == f); if( currentlyRunning ) { @@ -1061,7 +1061,7 @@ bool FolderMan::startFromScratch( const QString& localFolder ) if( fi.exists() ) { // It exists, but is empty -> just reuse it. if( fi.isDir() && fi.dir().count() == 0 ) { - qDebug() << "startFromScratch: Directory is empty!"; + qCDebug(lcFolderMan) << "startFromScratch: Directory is empty!"; return true; } // Disconnect the socket api from the database to avoid that locking of the @@ -1079,14 +1079,14 @@ bool FolderMan::startFromScratch( const QString& localFolder ) QString newName = getBackupName( parentDir.absoluteFilePath( folderName ) ); QString renameError; if( !FileSystem::rename( fi.absoluteFilePath(), newName, &renameError ) ) { - qDebug() << "startFromScratch: Could not rename" << fi.absoluteFilePath() + qCDebug(lcFolderMan) << "startFromScratch: Could not rename" << fi.absoluteFilePath() << "to" << newName << "error:" << renameError; return false; } } if( !parentDir.mkdir( fi.absoluteFilePath() ) ) { - qDebug() << "startFromScratch: Could not mkdir" << fi.absoluteFilePath(); + qCDebug(lcFolderMan) << "startFromScratch: Could not mkdir" << fi.absoluteFilePath(); return false; } @@ -1439,14 +1439,14 @@ void FolderMan::restartApplication() { if( Utility::isLinux() ) { // restart: - qDebug() << "### Restarting application NOW, PID" << qApp->applicationPid() << "is ending."; + qCDebug(lcFolderMan) << "### Restarting application NOW, PID" << qApp->applicationPid() << "is ending."; qApp->quit(); QStringList args = qApp->arguments(); QString prg = args.takeFirst(); QProcess::startDetached(prg, args); } else { - qDebug() << "On this platform we do not restart."; + qCDebug(lcFolderMan) << "On this platform we do not restart."; } } diff --git a/src/gui/folderstatusmodel.cpp b/src/gui/folderstatusmodel.cpp index 8eca32b61..969f23c61 100644 --- a/src/gui/folderstatusmodel.cpp +++ b/src/gui/folderstatusmodel.cpp @@ -29,6 +29,8 @@ Q_DECLARE_METATYPE(QPersistentModelIndex) namespace OCC { +Q_LOGGING_CATEGORY(lcFolderStatus, "gui.folder.model", QtInfoMsg) + static const char propertyParentIndexC[] = "oc_parentIndex"; static const char propertyPermissionMap[] = "oc_permissionMap"; @@ -624,7 +626,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list) auto selectiveSyncUndecidedList = parentInfo->_folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok2); if( !(ok1 && ok2) ) { - qDebug() << Q_FUNC_INFO << "Could not retrieve selective sync info from journal"; + qCDebug(lcFolderStatus) << "Could not retrieve selective sync info from journal"; return; } @@ -730,7 +732,7 @@ void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply* r) } auto parentInfo = infoForIndex(idx); if (parentInfo) { - qDebug() << r->errorString(); + qCDebug(lcFolderStatus) << r->errorString(); parentInfo->_lastErrorString = r->errorString(); parentInfo->resetSubs(this, idx); @@ -798,7 +800,7 @@ void FolderStatusModel::slotApplySelectiveSync() bool ok; auto oldBlackList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok); if( !ok ) { - qDebug() << Q_FUNC_INFO << "Could not read selective sync list from db."; + qCDebug(lcFolderStatus) << "Could not read selective sync list from db."; return; } QStringList blackList = createBlackList(&_folders[i], oldBlackList); @@ -894,10 +896,8 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) } if (citm._item._direction != SyncFileItem::Up){ estimatedDownBw += progress.fileProgress(citm._item).estimatedBandwidth; - //qDebug() << "DOWN" << citm._item._file << progress.fileProgress(citm._item).estimatedBandwidth; } else { estimatedUpBw += progress.fileProgress(citm._item).estimatedBandwidth; - //qDebug() << "UP" << citm._item._file << progress.fileProgress(citm._item).estimatedBandwidth; } auto fileName = QFileInfo(citm._item._file).fileName(); if (allFilenames.length() > 0) { @@ -908,7 +908,6 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) allFilenames.append(tr("'%1'").arg(fileName)); } } - //qDebug() << "Syncing bandwidth" << estimatedDownBw << estimatedUpBw; if (curItemProgress == -1) { curItemProgress = curItem._size; } @@ -1081,7 +1080,7 @@ void FolderStatusModel::slotSyncAllPendingBigFolders() bool ok; auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok); if( !ok ) { - qDebug() << Q_FUNC_INFO << "Could not read selective sync list from db."; + qCDebug(lcFolderStatus) << "Could not read selective sync list from db."; return; } @@ -1093,7 +1092,7 @@ void FolderStatusModel::slotSyncAllPendingBigFolders() // Remove all undecided folders from the blacklist auto blackList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok); if( !ok ) { - qDebug() << Q_FUNC_INFO << "Could not read selective sync list from db."; + qCDebug(lcFolderStatus) << "Could not read selective sync list from db."; return; } foreach (const auto& undecidedFolder, undecidedList) { @@ -1104,7 +1103,7 @@ void FolderStatusModel::slotSyncAllPendingBigFolders() // Add all undecided folders to the white list auto whiteList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok); if( !ok ) { - qDebug() << Q_FUNC_INFO << "Could not read selective sync list from db."; + qCDebug(lcFolderStatus) << "Could not read selective sync list from db."; return; } whiteList += undecidedList; diff --git a/src/gui/folderstatusmodel.h b/src/gui/folderstatusmodel.h index 5071e1e30..197c82e65 100644 --- a/src/gui/folderstatusmodel.h +++ b/src/gui/folderstatusmodel.h @@ -17,12 +17,15 @@ #include #include +#include #include #include class QNetworkReply; namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcFolderStatus) + class Folder; class ProgressInfo; diff --git a/src/gui/folderwatcher.cpp b/src/gui/folderwatcher.cpp index c5b4f6ea5..cd4a5c9ad 100644 --- a/src/gui/folderwatcher.cpp +++ b/src/gui/folderwatcher.cpp @@ -19,7 +19,6 @@ #include #include -#include #include #include #include @@ -38,6 +37,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcFolderWatcher, "gui.folderwatcher", QtInfoMsg) + FolderWatcher::FolderWatcher(const QString &root, Folder* folder) : QObject(folder), _folder(folder) @@ -57,7 +58,7 @@ bool FolderWatcher::pathIsIgnored( const QString& path ) #ifndef OWNCLOUD_TEST if (_folder->isFileExcludedAbsolute(path)) { - qDebug() << "* Ignoring file" << path; + qCDebug(lcFolderWatcher) << "* Ignoring file" << path; return true; } #endif @@ -72,8 +73,6 @@ void FolderWatcher::changeDetected( const QString& path ) void FolderWatcher::changeDetected( const QStringList& paths ) { - // qDebug() << Q_FUNC_INFO << paths; - // TODO: this shortcut doesn't look very reliable: // - why is the timeout only 1 second? // - what if there is more than one file being updated frequently? @@ -103,7 +102,7 @@ void FolderWatcher::changeDetected( const QStringList& paths ) return; } - qDebug() << "detected changes in paths:" << changedPaths; + qCDebug(lcFolderWatcher) << "detected changes in paths:" << changedPaths; foreach (const QString &path, changedPaths) { emit pathChanged(path); } diff --git a/src/gui/folderwatcher.h b/src/gui/folderwatcher.h index 3fceffc5b..3f1d1a981 100644 --- a/src/gui/folderwatcher.h +++ b/src/gui/folderwatcher.h @@ -18,6 +18,7 @@ #include "config.h" #include +#include #include #include #include @@ -30,6 +31,8 @@ class QTimer; namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcFolderWatcher) + class FolderWatcherPrivate; class Folder; diff --git a/src/gui/folderwatcher_linux.cpp b/src/gui/folderwatcher_linux.cpp index c8024c00b..0635ae244 100644 --- a/src/gui/folderwatcher_linux.cpp +++ b/src/gui/folderwatcher_linux.cpp @@ -20,7 +20,6 @@ #include "folderwatcher_linux.h" #include -#include #include #include #include @@ -37,7 +36,7 @@ FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path _socket.reset( new QSocketNotifier(_fd, QSocketNotifier::Read) ); connect(_socket.data(), SIGNAL(activated(int)), SLOT(slotReceivedNotification(int))); } else { - qDebug() << Q_FUNC_INFO << "notify_init() failed: " << strerror(errno); + qCDebug(lcFolderWatcher) << "notify_init() failed: " << strerror(errno); } QMetaObject::invokeMethod(this, "slotAddFolderRecursive", Q_ARG(QString, path)); @@ -54,7 +53,7 @@ bool FolderWatcherPrivate::findFoldersBelow( const QDir& dir, QStringList& fullL { bool ok = true; if( !(dir.exists() && dir.isReadable()) ) { - qDebug() << "Non existing path coming in: " << dir.absolutePath(); + qCDebug(lcFolderWatcher) << "Non existing path coming in: " << dir.absolutePath(); ok = false; } else { QStringList nameFilter; @@ -90,7 +89,7 @@ void FolderWatcherPrivate::inotifyRegisterPath(const QString& path) void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path) { int subdirs = 0; - qDebug() << "(+) Watcher:" << path; + qCDebug(lcFolderWatcher) << "(+) Watcher:" << path; QDir inPath(path); inotifyRegisterPath(inPath.absolutePath()); @@ -99,28 +98,26 @@ void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path) QStringList allSubfolders; if( !findFoldersBelow(QDir(path), allSubfolders)) { - qDebug() << "Could not traverse all sub folders"; + qCDebug(lcFolderWatcher) << "Could not traverse all sub folders"; } - // qDebug() << "currently watching " << watchedFolders; QStringListIterator subfoldersIt(allSubfolders); while (subfoldersIt.hasNext()) { QString subfolder = subfoldersIt.next(); - // qDebug() << " (**) subfolder: " << subfolder; QDir folder (subfolder); if (folder.exists() && !watchedFolders.contains(folder.absolutePath())) { subdirs++; if( _parent->pathIsIgnored(subfolder) ) { - qDebug() << "* Not adding" << folder.path(); + qCDebug(lcFolderWatcher) << "* Not adding" << folder.path(); continue; } inotifyRegisterPath(folder.absolutePath()); } else { - qDebug() << " `-> discarded:" << folder.path(); + qCDebug(lcFolderWatcher) << " `-> discarded:" << folder.path(); } } if (subdirs >0) { - qDebug() << " `-> and" << subdirs << "subdirectories"; + qCDebug(lcFolderWatcher) << " `-> and" << subdirs << "subdirectories"; } } @@ -160,7 +157,7 @@ void FolderWatcherPrivate::slotReceivedNotification(int fd) // cast an inotify_event event = (struct inotify_event*)&buffer[i]; if (event == NULL) { - qDebug() << "NULL event"; + qCDebug(lcFolderWatcher) << "NULL event"; i += sizeof(struct inotify_event); continue; } @@ -168,14 +165,11 @@ void FolderWatcherPrivate::slotReceivedNotification(int fd) // Fire event for the path that was changed. if (event->len > 0 && event->wd > -1) { QByteArray fileName(event->name); - // qDebug() << Q_FUNC_INFO << event->name; if (fileName.startsWith("._sync_") || fileName.startsWith(".csync_journal.db") || fileName.startsWith(".owncloudsync.log")) { - // qDebug() << "ignore journal"; } else { const QString p = _watches[event->wd] + '/' + fileName; - //qDebug() << "found a change in " << p; _parent->changeDetected(p); } } diff --git a/src/gui/folderwatcher_mac.cpp b/src/gui/folderwatcher_mac.cpp index 6973536c8..d18ad8dba 100644 --- a/src/gui/folderwatcher_mac.cpp +++ b/src/gui/folderwatcher_mac.cpp @@ -19,7 +19,6 @@ #include -#include #include @@ -60,7 +59,7 @@ static void callback( | kFSEventStreamEventFlagItemModified; // for content change //We ignore other flags, e.g. for owner change, xattr change, Finder label change etc - qDebug() << "FolderWatcherPrivate::callback by OS X"; + qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::callback by OS X"; QStringList paths; CFArrayRef eventPaths = (CFArrayRef)eventPathsVoid; @@ -74,7 +73,7 @@ static void callback( QString fn = qstring.normalized(QString::NormalizationForm_C); if (!(eventFlags[i] & c_interestingFlags)) { - qDebug() << "Ignoring non-content changes for" << fn; + qCDebug(lcFolderWatcher) << "Ignoring non-content changes for" << fn; continue; } @@ -86,7 +85,7 @@ static void callback( void FolderWatcherPrivate::startWatching() { - qDebug() << "FolderWatcherPrivate::startWatching()" << _folder; + qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::startWatching()" << _folder; CFStringRef folderCF = CFStringCreateWithCharacters(0, reinterpret_cast(_folder.unicode()), _folder.length()); CFArrayRef pathsToWatch = CFStringCreateArrayBySeparatingStrings (NULL, folderCF, CFSTR(":")); diff --git a/src/gui/folderwatcher_win.cpp b/src/gui/folderwatcher_win.cpp index 173fb5680..b6fa82d63 100644 --- a/src/gui/folderwatcher_win.cpp +++ b/src/gui/folderwatcher_win.cpp @@ -13,7 +13,6 @@ */ #include -#include #include #include "filesystem.h" @@ -45,7 +44,7 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, if (_directory == INVALID_HANDLE_VALUE) { DWORD errorCode = GetLastError(); - qDebug() << Q_FUNC_INFO << "Failed to create handle for" << _path << ", error:" << errorCode; + qCDebug(lcFolderWatcher) << "Failed to create handle for" << _path << ", error:" << errorCode; _directory = 0; return; } @@ -79,11 +78,11 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, { DWORD errorCode = GetLastError(); if (errorCode == ERROR_NOTIFY_ENUM_DIR) { - qDebug() << Q_FUNC_INFO << "The buffer for changes overflowed! Triggering a generic change and resizing"; + qCDebug(lcFolderWatcher) << "The buffer for changes overflowed! Triggering a generic change and resizing"; emit changed(_path); *increaseBufferSize = true; } else { - qDebug() << Q_FUNC_INFO << "ReadDirectoryChangesW error" << errorCode; + qCDebug(lcFolderWatcher) << "ReadDirectoryChangesW error" << errorCode; } break; } @@ -94,11 +93,11 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, false, // awake once one of them arrives INFINITE); if (result == 1) { - qDebug() << "Received stop event, aborting folder watcher thread"; + qCDebug(lcFolderWatcher) << "Received stop event, aborting folder watcher thread"; break; } if (result != 0) { - qDebug() << "WaitForMultipleObjects failed" << result << GetLastError(); + qCDebug(lcFolderWatcher) << "WaitForMultipleObjects failed" << result << GetLastError(); break; } @@ -106,11 +105,11 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, if (! ok) { DWORD errorCode = GetLastError(); if (errorCode == ERROR_NOTIFY_ENUM_DIR) { - qDebug() << Q_FUNC_INFO << "The buffer for changes overflowed! Triggering a generic change and resizing"; + qCDebug(lcFolderWatcher) << "The buffer for changes overflowed! Triggering a generic change and resizing"; emit changed(_path); *increaseBufferSize = true; } else { - qDebug() << Q_FUNC_INFO << "GetOverlappedResult error" << errorCode; + qCDebug(lcFolderWatcher) << "GetOverlappedResult error" << errorCode; } break; } @@ -129,7 +128,7 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, if (longNameSize > 0) { longfile = QString::fromUtf16(reinterpret_cast(fileNameBuffer), longNameSize); } else { - qDebug() << Q_FUNC_INFO << "Error converting file name to full length, keeping original name."; + qCDebug(lcFolderWatcher) << "Error converting file name to full length, keeping original name."; } } longfile = QDir::cleanPath(longfile); @@ -141,8 +140,6 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, && QFileInfo(longfile).isDir(); if (!skip) { - //qDebug() << Q_FUNC_INFO << "Found change in" << longfile - // << "action:" << curEntry->Action; emit changed(longfile); } diff --git a/src/gui/folderwizard.cpp b/src/gui/folderwizard.cpp index 18eafa33b..eada127e1 100644 --- a/src/gui/folderwizard.cpp +++ b/src/gui/folderwizard.cpp @@ -21,8 +21,8 @@ #include "selectivesyncdialog.h" #include "accountstate.h" #include "creds/abstractcredentials.h" +#include "wizard/owncloudwizard.h" -#include #include #include #include @@ -209,7 +209,7 @@ void FolderWizardRemotePath::slotCreateRemoteFolder(const QString &folder) void FolderWizardRemotePath::slotCreateRemoteFolderFinished(QNetworkReply::NetworkError error) { if (error == QNetworkReply::NoError) { - qDebug() << "** webdav mkdir request finished"; + qCDebug(lcWizard) << "webdav mkdir request finished"; showWarn(tr("Folder was successfully created on %1.").arg(Theme::instance()->appNameGUI())); slotRefreshFolders(); _ui.folderEntry->setText(static_cast(sender())->path()); @@ -219,7 +219,7 @@ void FolderWizardRemotePath::slotCreateRemoteFolderFinished(QNetworkReply::Netwo void FolderWizardRemotePath::slotHandleMkdirNetworkError(QNetworkReply *reply) { - qDebug() << "** webdav mkdir request failed:" << reply->error(); + qCDebug(lcWizard) << "webdav mkdir request failed:" << reply->error(); if( !_account->credentials()->stillValid(reply) ) { showWarn(tr("Authentication failed accessing %1").arg(Theme::instance()->appNameGUI())); } else { diff --git a/src/gui/lockwatcher.cpp b/src/gui/lockwatcher.cpp index 066d45a88..55e6bcbba 100644 --- a/src/gui/lockwatcher.cpp +++ b/src/gui/lockwatcher.cpp @@ -15,11 +15,13 @@ #include "lockwatcher.h" #include "filesystem.h" +#include #include -#include using namespace OCC; +Q_LOGGING_CATEGORY(lcLockWatcher, "gui.lockwatcher", QtInfoMsg) + static const int check_frequency = 20 * 1000; // ms LockWatcher::LockWatcher(QObject* parent) @@ -32,7 +34,7 @@ LockWatcher::LockWatcher(QObject* parent) void LockWatcher::addFile(const QString& path) { - qDebug() << "Watching for lock of" << path << "being released"; + qCDebug(lcLockWatcher) << "Watching for lock of" << path << "being released"; _watchedPaths.insert(path); } @@ -42,7 +44,7 @@ void LockWatcher::checkFiles() foreach (const QString& path, _watchedPaths) { if (!FileSystem::isFileLocked(path)) { - qDebug() << "Lock of" << path << "was released"; + qCDebug(lcLockWatcher) << "Lock of" << path << "was released"; emit fileUnlocked(path); unlocked.insert(path); } diff --git a/src/gui/logbrowser.cpp b/src/gui/logbrowser.cpp index 22e17f80d..a5cf44c24 100644 --- a/src/gui/logbrowser.cpp +++ b/src/gui/logbrowser.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include @@ -122,7 +121,6 @@ LogBrowser::LogBrowser(QWidget *parent) : ConfigFile cfg; cfg.restoreGeometry(this); int lines = cfg.maxLogLines(); - // qDebug() << "# ## Have " << lines << " Loglines!"; _logWidget->document()->setMaximumBlockCount( lines ); } diff --git a/src/gui/main.cpp b/src/gui/main.cpp index 392ced1b5..0155c1a60 100644 --- a/src/gui/main.cpp +++ b/src/gui/main.cpp @@ -100,7 +100,7 @@ int main(int argc, char **argv) if (setrlimit(RLIMIT_CORE, &core_limit) < 0) { fprintf(stderr, "Unable to set core dump limit\n"); } else { - qDebug() << "Core dumps enabled"; + qCDebug(lcApplication) << "Core dumps enabled"; } } #endif @@ -114,10 +114,10 @@ int main(int argc, char **argv) // if the application is already running, notify it. if(app.isRunning()) { - qDebug() << Q_FUNC_INFO << "Already running, exiting..."; + qCDebug(lcApplication) << "Already running, exiting..."; if (app.isSessionRestored()) { // This call is mirrored with the one in Application::slotParseMessage - qDebug() << "Session was restored, don't notify app!"; + qCDebug(lcApplication) << "Session was restored, don't notify app!"; return -1; } diff --git a/src/gui/notificationconfirmjob.cpp b/src/gui/notificationconfirmjob.cpp index 86721d98b..eb8ee25cd 100644 --- a/src/gui/notificationconfirmjob.cpp +++ b/src/gui/notificationconfirmjob.cpp @@ -20,6 +20,8 @@ namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcNotifications) + NotificationConfirmJob::NotificationConfirmJob(AccountPtr account) : AbstractNetworkJob(account, ""), _widget(0) @@ -46,7 +48,7 @@ NotificationWidget *NotificationConfirmJob::widget() void NotificationConfirmJob::start() { if( !_link.isValid() ) { - qDebug() << "Attempt to trigger invalid URL: " << _link.toString(); + qCDebug(lcNotifications) << "Attempt to trigger invalid URL: " << _link.toString(); return; } QNetworkRequest req; diff --git a/src/gui/notificationwidget.cpp b/src/gui/notificationwidget.cpp index 7aa317802..f247ec2c5 100644 --- a/src/gui/notificationwidget.cpp +++ b/src/gui/notificationwidget.cpp @@ -23,6 +23,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcNotifications, "gui.notifications", QtInfoMsg) + NotificationWidget::NotificationWidget(QWidget *parent) : QWidget(parent) { _ui.setupUi(this); @@ -109,7 +111,7 @@ void NotificationWidget::slotButtonClicked() _actionLabel = triggeredLink._label; if( ! triggeredLink._link.isEmpty() ) { - qDebug() << Q_FUNC_INFO << "Notification Link: "<< triggeredLink._verb << triggeredLink._link; + qCDebug(lcNotifications) << "Notification Link: "<< triggeredLink._verb << triggeredLink._link; _progressIndi->startAnimation(); emit sendNotificationRequest( _accountName, triggeredLink._link, triggeredLink._verb ); } @@ -127,7 +129,7 @@ void NotificationWidget::slotNotificationRequestFinished(int statusCode) // the ocs API returns stat code 100 if it succeeded. if( statusCode != OCS_SUCCESS_STATUS_CODE ) { - qDebug() << Q_FUNC_INFO << "Notification Request to Server failed, leave button visible."; + qCDebug(lcNotifications) << "Notification Request to Server failed, leave button visible."; for( i = 0; i < _buttons.count(); i++ ) { _buttons.at(i)->setEnabled(true); } diff --git a/src/gui/ocsjob.cpp b/src/gui/ocsjob.cpp index a513308cc..897ec1c64 100644 --- a/src/gui/ocsjob.cpp +++ b/src/gui/ocsjob.cpp @@ -22,6 +22,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcOcs, "gui.sharing.ocs", QtInfoMsg) + OcsJob::OcsJob(AccountPtr account) : AbstractNetworkJob(account, "") { @@ -105,7 +107,7 @@ bool OcsJob::finished() QJsonParseError error; auto json = QJsonDocument::fromJson(replyData, &error); if (error.error != QJsonParseError::NoError) { - qDebug() << "Could not parse reply to" + qCDebug(lcOcs) << "Could not parse reply to" << _verb << Utility::concatUrlPath(account()->url(), path()) << _params @@ -116,7 +118,7 @@ bool OcsJob::finished() QString message; const int statusCode = getJsonReturnCode(json, message); if (!_passStatusCodes.contains(statusCode)) { - qDebug() << "Reply to" + qCDebug(lcOcs) << "Reply to" << _verb << Utility::concatUrlPath(account()->url(), path()) << _params diff --git a/src/gui/openfilemanager.cpp b/src/gui/openfilemanager.cpp index 3430f6c30..84e066e12 100644 --- a/src/gui/openfilemanager.cpp +++ b/src/gui/openfilemanager.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include namespace OCC { @@ -103,7 +102,6 @@ void showInFileManager(const QString &localPath) nativeArgs += QDir::toNativeSeparators(fi.canonicalFilePath()); nativeArgs += QLatin1Char('"'); - qDebug() << "OO Open explorer commandline:" << explorer << nativeArgs; QProcess p; #ifdef Q_OS_WIN // QProcess on Windows tries to wrap the whole argument/program string diff --git a/src/gui/owncloudgui.cpp b/src/gui/owncloudgui.cpp index c80b34628..e8dab0eb2 100644 --- a/src/gui/owncloudgui.cpp +++ b/src/gui/owncloudgui.cpp @@ -139,10 +139,10 @@ void ownCloudGui::setupOverlayIcons() p.waitForFinished(5000); QByteArray result = p.readAll(); QString resultAsString(result); // if appropriate - qDebug() << "Load Finder Overlay-Plugin: " << resultAsString << ": " << p.exitCode() + qCDebug(lcApplication) << "Load Finder Overlay-Plugin: " << resultAsString << ": " << p.exitCode() << (p.exitCode() != 0 ? p.errorString() : QString::null); } else { - qDebug() << finderExtension << "does not exist! Finder Overlay Plugin loading failed"; + qCDebug(lcApplication) << finderExtension << "does not exist! Finder Overlay Plugin loading failed"; } } #endif @@ -159,7 +159,7 @@ void ownCloudGui::slotOpenSettingsDialog() _settingsDialog->close(); } } else { - qDebug() << "No configured folders yet, starting setup wizard"; + qCDebug(lcApplication) << "No configured folders yet, starting setup wizard"; slotNewAccountWizard(); } } @@ -212,7 +212,7 @@ void ownCloudGui::slotSyncStateChange( Folder* folder ) auto result = folder->syncResult(); - qDebug() << "Sync state changed for folder " << folder->remoteUrl().toString() << ": " << result.statusString(); + qCDebug(lcApplication) << "Sync state changed for folder " << folder->remoteUrl().toString() << ": " << result.statusString(); if (result.status() == SyncResult::Success || result.status() == SyncResult::Error) { Logger::instance()->enterNextLogFile(); @@ -323,7 +323,6 @@ void ownCloudGui::slotComputeOverallSyncStatus() #else QStringList allStatusStrings; foreach(Folder* folder, map.values()) { - //qDebug() << "Folder in overallStatus Message: " << folder << " with name " << folder->alias(); QString folderMessage = folderMan->statusToString(folder->syncResult().status(), folder->syncPaused()); allStatusStrings += tr("Folder %1: %2").arg(folder->shortGuiLocalPath(), folderMessage); } @@ -413,7 +412,6 @@ void ownCloudGui::addAccountContextMenu(AccountStatePtr accountState, QMenu *men void ownCloudGui::slotContextMenuAboutToShow() { // For some reason on OS X _contextMenu->isVisible returns always false - qDebug() << ""; _contextMenuVisibleOsx = true; // Update icon in sys tray, as it might change depending on the context menu state @@ -423,7 +421,6 @@ void ownCloudGui::slotContextMenuAboutToShow() void ownCloudGui::slotContextMenuAboutToHide() { // For some reason on OS X _contextMenu->isVisible returns always false - qDebug() << ""; _contextMenuVisibleOsx = false; // Update icon in sys tray, as it might change depending on the context menu state @@ -503,7 +500,7 @@ void ownCloudGui::setupContextMenu() if (platformMenu && platformMenu->metaObject()->className() == QLatin1String("QDBusPlatformMenu")) { _qdbusmenuWorkaround = true; - qDebug() << "Enabled QDBusPlatformMenu workaround"; + qCDebug(lcApplication) << "Enabled QDBusPlatformMenu workaround"; } } #endif @@ -696,7 +693,7 @@ void ownCloudGui::slotShowTrayMessage(const QString &title, const QString &msg) if( _tray ) _tray->showMessage(title, msg); else - qDebug() << "Tray not ready: " << msg; + qCDebug(lcApplication) << "Tray not ready: " << msg; } void ownCloudGui::slotShowOptionalTrayMessage(const QString &title, const QString &msg) @@ -715,7 +712,7 @@ void ownCloudGui::slotFolderOpenAction( const QString& alias ) { Folder *f = FolderMan::instance()->folder(alias); if( f ) { - qDebug() << "opening local url " << f->path(); + qCDebug(lcApplication) << "opening local url " << f->path(); QUrl url = QUrl::fromLocalFile(f->path()); #ifdef Q_OS_WIN @@ -943,7 +940,6 @@ void ownCloudGui::slotShowGuiMessage(const QString &title, const QString &messag void ownCloudGui::slotShowSettings() { - qDebug() << Q_FUNC_INFO; if (_settingsDialog.isNull()) { _settingsDialog = #if defined(Q_OS_MAC) @@ -1043,7 +1039,7 @@ void ownCloudGui::slotShowShareDialog(const QString &sharePath, const QString &l { const auto folder = FolderMan::instance()->folderForPath(localPath); if (!folder) { - qDebug() << "Could not open share dialog for" << localPath << "no responsible folder found"; + qCDebug(lcApplication) << "Could not open share dialog for" << localPath << "no responsible folder found"; return; } @@ -1068,10 +1064,10 @@ void ownCloudGui::slotShowShareDialog(const QString &sharePath, const QString &l ShareDialog *w = 0; if (_shareDialogs.contains(localPath) && _shareDialogs[localPath]) { - qDebug() << Q_FUNC_INFO << "Raising share dialog" << sharePath << localPath; + qCDebug(lcApplication) << "Raising share dialog" << sharePath << localPath; w = _shareDialogs[localPath]; } else { - qDebug() << Q_FUNC_INFO << "Opening share dialog" << sharePath << localPath << maxSharingPermissions; + qCDebug(lcApplication) << "Opening share dialog" << sharePath << localPath << maxSharingPermissions; w = new ShareDialog(accountState, sharePath, localPath, maxSharingPermissions); w->setAttribute( Qt::WA_DeleteOnClose, true ); @@ -1088,7 +1084,6 @@ void ownCloudGui::slotRemoveDestroyedShareDialogs() it.next(); if (! it.value() || it.value() == sender()) { it.remove(); - qDebug() << "REMOVED"; } } } diff --git a/src/gui/owncloudsetupwizard.cpp b/src/gui/owncloudsetupwizard.cpp index 62eb21d11..cde42a53d 100644 --- a/src/gui/owncloudsetupwizard.cpp +++ b/src/gui/owncloudsetupwizard.cpp @@ -144,7 +144,7 @@ void OwncloudSetupWizard::slotDetermineAuthType(const QString &urlString) // Lookup system proxy in a thread https://github.com/owncloud/client/issues/2993 if (ClientProxy::isUsingSystemDefault()) { - qDebug() << "Trying to look up system proxy"; + qCDebug(lcWizard) << "Trying to look up system proxy"; ClientProxy::lookupSystemProxyAsync(account->url(), this, SLOT(slotSystemProxyLookupDone(QNetworkProxy))); } else { @@ -158,9 +158,9 @@ void OwncloudSetupWizard::slotDetermineAuthType(const QString &urlString) void OwncloudSetupWizard::slotSystemProxyLookupDone(const QNetworkProxy &proxy) { if (proxy.type() != QNetworkProxy::NoProxy) { - qDebug() << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy); + qCDebug(lcWizard) << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy); } else { - qDebug() << "No system proxy set by OS"; + qCDebug(lcWizard) << "No system proxy set by OS"; } AccountPtr account = _ocWizard->account(); account->networkAccessManager()->setProxy(proxy); @@ -203,7 +203,7 @@ void OwncloudSetupWizard::slotOwnCloudFoundAuth(const QUrl& url, const QJsonObje QUrl redirectedUrl = url; redirectedUrl.setPath(url.path().left(url.path().length() - 11)); _ocWizard->account()->setUrl(redirectedUrl); - qDebug() << Q_FUNC_INFO << " was redirected to" << redirectedUrl.toString(); + qCDebug(lcWizard) << " was redirected to" << redirectedUrl.toString(); } DetermineAuthTypeJob *job = new DetermineAuthTypeJob(_ocWizard->account(), this); @@ -239,7 +239,7 @@ void OwncloudSetupWizard::slotNoOwnCloudFoundAuth(QNetworkReply *reply) // FIXME: Synchronous dialogs are not so nice because of event loop recursion // (we already create a dialog further below) QString serverError = reply->peek(1024*20); - qDebug() << serverError; + qCDebug(lcWizard) << serverError; QMessageBox messageBox(_ocWizard); messageBox.setText(serverError); messageBox.addButton(QMessageBox::Ok); @@ -265,7 +265,7 @@ void OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout(const QUrl&url) void OwncloudSetupWizard::slotConnectToOCUrl( const QString& url ) { - qDebug() << "Connect to url: " << url; + qCDebug(lcWizard) << "Connect to url: " << url; AbstractCredentials *creds = _ocWizard->getCredentials(); _ocWizard->account()->setCredentials(creds); _ocWizard->setField(QLatin1String("OCUrl"), url ); @@ -296,7 +296,7 @@ void OwncloudSetupWizard::slotAuthError() PropfindJob* job = qobject_cast(sender()); if (!job) { - qWarning() << "Can't check for authed redirects. This slot should be invoked from PropfindJob!"; + qCWarning(lcWizard) << "Can't check for authed redirects. This slot should be invoked from PropfindJob!"; return; } QNetworkReply* reply = job->reply(); @@ -305,7 +305,7 @@ void OwncloudSetupWizard::slotAuthError() // the updated server URL, similar to redirects on status.php. QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!redirectUrl.isEmpty()) { - qDebug() << "authed request was redirected to" << redirectUrl.toString(); + qCDebug(lcWizard) << "authed request was redirected to" << redirectUrl.toString(); // strip the expected path QString path = redirectUrl.path(); @@ -314,7 +314,7 @@ void OwncloudSetupWizard::slotAuthError() path.chop(expectedPath.size()); redirectUrl.setPath(path); - qDebug() << "setting account url to" << redirectUrl.toString(); + qCDebug(lcWizard) << "setting account url to" << redirectUrl.toString(); _ocWizard->account()->setUrl(redirectUrl); testOwnCloudConnect(); return; @@ -376,7 +376,7 @@ bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply* reply) void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFolder, const QString& remoteFolder) { - qDebug() << "Setup local sync folder for new oC connection " << localFolder; + qCDebug(lcWizard) << "Setup local sync folder for new oC connection " << localFolder; const QDir fi( localFolder ); bool nextStep = true; @@ -395,7 +395,7 @@ void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFo res += tr("ok"); } else { res += tr("failed."); - qDebug() << "Failed to create " << fi.path(); + qCDebug(lcWizard) << "Failed to create " << fi.path(); _ocWizard->displayError(tr("Could not create local folder %1").arg(Utility::escape(localFolder)), false); nextStep = false; } @@ -419,7 +419,7 @@ void OwncloudSetupWizard::slotRemoteFolderExists(QNetworkReply *reply) QNetworkReply::NetworkError errId = reply->error(); if( errId == QNetworkReply::NoError ) { - qDebug() << "******** Remote folder found, all cool!"; + qCDebug(lcWizard) << "******** Remote folder found, all cool!"; } else if( errId == QNetworkReply::ContentNotFoundError ) { if( _remoteFolder.isEmpty() ) { error = tr("No remote folder specified!"); @@ -450,7 +450,7 @@ void OwncloudSetupWizard::createRemoteFolder() void OwncloudSetupWizard::slotCreateRemoteFolderFinished( QNetworkReply::NetworkError error ) { - qDebug() << "** webdav mkdir request finished " << error; + qCDebug(lcWizard) << "** webdav mkdir request finished " << error; // disconnect(ownCloudInfo::instance(), SIGNAL(webdavColCreated(QNetworkReply::NetworkError)), // this, SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError))); @@ -533,7 +533,7 @@ void OwncloudSetupWizard::slotAssistantFinished( int result ) FolderMan *folderMan = FolderMan::instance(); if( result == QDialog::Rejected ) { - qDebug() << "Rejected the new config, use the old!"; + qCDebug(lcWizard) << "Rejected the new config, use the old!"; } else if( result == QDialog::Accepted ) { // This may or may not wipe all folder definitions, depending @@ -545,7 +545,7 @@ void OwncloudSetupWizard::slotAssistantFinished( int result ) bool startFromScratch = _ocWizard->field("OCSyncFromScratch").toBool(); if (!startFromScratch || ensureStartFromScratch(localFolder)) { - qDebug() << "Adding folder definition for" << localFolder << _remoteFolder; + qCDebug(lcWizard) << "Adding folder definition for" << localFolder << _remoteFolder; FolderDefinition folderDefinition; folderDefinition.localPath = localFolder; folderDefinition.targetPath = FolderDefinition::prepareTargetPath(_remoteFolder); @@ -616,7 +616,7 @@ void DetermineAuthTypeJob::start() bool DetermineAuthTypeJob::finished() { QUrl redirection = reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); - qDebug() << Q_FUNC_INFO << redirection.toString(); + qCDebug(lcWizard) << redirection.toString(); if (_redirects >= maxRedirects()) { redirection.clear(); } diff --git a/src/gui/proxyauthhandler.cpp b/src/gui/proxyauthhandler.cpp index e80b540e8..56fe87d35 100644 --- a/src/gui/proxyauthhandler.cpp +++ b/src/gui/proxyauthhandler.cpp @@ -25,6 +25,8 @@ using namespace OCC; +Q_LOGGING_CATEGORY(lcProxy, "gui.credentials.proxy", QtInfoMsg) + ProxyAuthHandler* ProxyAuthHandler::instance() { static ProxyAuthHandler inst; @@ -91,11 +93,11 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired( sending_qnam = qnam_alive.data(); } if (!sending_qnam) { - qDebug() << "Could not get the sending QNAM for" << sender(); + qCDebug(lcProxy) << "Could not get the sending QNAM for" << sender(); } - qDebug() << Q_FUNC_INFO << key << proxy.type(); + qCDebug(lcProxy) << "Proxy auth required for" << key << proxy.type(); // If we already had a username but auth still failed, // invalidate the old credentials! Unfortunately, authenticator->user() @@ -105,7 +107,7 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired( if (!_waitingForDialog && !_waitingForKeychain && (!authenticator->user().isEmpty() || (sending_qnam && _gaveCredentialsTo.contains(sending_qnam)))) { - qDebug() << "invalidating old creds" << key; + qCDebug(lcProxy) << "invalidating old creds" << key; _username.clear(); _password.clear(); invalidated = true; @@ -124,7 +126,7 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired( } } - qDebug() << "got creds for" << _proxy; + qCDebug(lcProxy) << "got creds for" << _proxy; authenticator->setUser(_username); authenticator->setPassword(_password); sending_qnam = qnam_alive.data(); @@ -164,7 +166,7 @@ bool ProxyAuthHandler::getCredsFromDialog() --_waitingForDialog; if (_dialog && _dialog->result() == QDialog::Accepted) { - qDebug() << "got creds for" << _proxy << "from dialog"; + qCDebug(lcProxy) << "got creds for" << _proxy << "from dialog"; _username = _dialog->username(); _password = _dialog->password(); return true; @@ -180,7 +182,7 @@ bool ProxyAuthHandler::getCredsFromKeychain() return false; } - qDebug() << "trying to load" << _proxy; + qCDebug(lcProxy) << "trying to load" << _proxy; if (!_waitingForKeychain) { _username = _settings->value(keychainUsernameKey()).toString(); @@ -211,14 +213,14 @@ bool ProxyAuthHandler::getCredsFromKeychain() --_waitingForKeychain; if (_readPasswordJob->error() == NoError) { - qDebug() << "got creds for" << _proxy << "from keychain"; + qCDebug(lcProxy) << "got creds for" << _proxy << "from keychain"; _password = _readPasswordJob->textData(); return true; } _username.clear(); if (_readPasswordJob->error() != EntryNotFound) { - qDebug() << "ReadPasswordJob failed with" << _readPasswordJob->errorString(); + qCDebug(lcProxy) << "ReadPasswordJob failed with" << _readPasswordJob->errorString(); } return false; } @@ -231,7 +233,7 @@ void ProxyAuthHandler::storeCredsInKeychain() return; } - qDebug() << "storing" << _proxy; + qCDebug(lcProxy) << "storing" << _proxy; _settings->setValue(keychainUsernameKey(), _username); @@ -254,7 +256,7 @@ void ProxyAuthHandler::storeCredsInKeychain() job->deleteLater(); if (job->error() != NoError) { - qDebug() << "WritePasswordJob failed with" << job->errorString(); + qCDebug(lcProxy) << "WritePasswordJob failed with" << job->errorString(); } } diff --git a/src/gui/quotainfo.cpp b/src/gui/quotainfo.cpp index cab65f49b..f2ccb2c55 100644 --- a/src/gui/quotainfo.cpp +++ b/src/gui/quotainfo.cpp @@ -21,7 +21,6 @@ #include #include -#include namespace OCC { diff --git a/src/gui/selectivesyncdialog.cpp b/src/gui/selectivesyncdialog.cpp index 4f23e248b..c10331723 100644 --- a/src/gui/selectivesyncdialog.cpp +++ b/src/gui/selectivesyncdialog.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #include #include #include diff --git a/src/gui/servernotificationhandler.cpp b/src/gui/servernotificationhandler.cpp index 6cb4ff490..bb28f4f74 100644 --- a/src/gui/servernotificationhandler.cpp +++ b/src/gui/servernotificationhandler.cpp @@ -23,6 +23,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcServerNotification, "gui.servernotification", QtInfoMsg) + ServerNotificationHandler::ServerNotificationHandler(QObject *parent) : QObject(parent) { @@ -42,7 +44,7 @@ void ServerNotificationHandler::slotFetchNotifications(AccountState *ptr) // not yet valid, its assumed that notifications are available. if( ptr->account()->capabilities().isValid() ) { if( ! ptr->account()->capabilities().notificationsAvailable() ) { - qDebug() << Q_FUNC_INFO << "Account" << ptr->account()->displayName() << "does not have notifications enabled."; + qCDebug(lcServerNotification) << "Account" << ptr->account()->displayName() << "does not have notifications enabled."; deleteLater(); return; } @@ -60,7 +62,7 @@ void ServerNotificationHandler::slotFetchNotifications(AccountState *ptr) void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument& json, int statusCode) { if( statusCode != 200 ) { - qDebug() << Q_FUNC_INFO << "Notifications failed with status code " << statusCode; + qCDebug(lcServerNotification) << "Notifications failed with status code " << statusCode; deleteLater(); return; } diff --git a/src/gui/settingsdialog.cpp b/src/gui/settingsdialog.cpp index 9a0501095..6c9fc1b54 100644 --- a/src/gui/settingsdialog.cpp +++ b/src/gui/settingsdialog.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include #include #include diff --git a/src/gui/settingsdialogmac.cpp b/src/gui/settingsdialogmac.cpp index ac65dae7a..65ae6ac38 100644 --- a/src/gui/settingsdialogmac.cpp +++ b/src/gui/settingsdialogmac.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include #include #include diff --git a/src/gui/sharedialog.cpp b/src/gui/sharedialog.cpp index a2bd34a37..2889379c0 100644 --- a/src/gui/sharedialog.cpp +++ b/src/gui/sharedialog.cpp @@ -13,6 +13,7 @@ */ #include "sharedialog.h" +#include "sharee.h" #include "sharelinkwidget.h" #include "shareusergroupwidget.h" #include "ui_sharedialog.h" @@ -25,7 +26,6 @@ #include #include -#include #include #include #include @@ -144,7 +144,7 @@ void ShareDialog::slotMaxSharingPermissionsReceived(const QVariantMap & result) const QVariant receivedPermissions = result["share-permissions"]; if (!receivedPermissions.toString().isEmpty()) { _maxSharingPermissions = static_cast(receivedPermissions.toInt()); - qDebug() << "Received sharing permissions for" << _sharePath << _maxSharingPermissions; + qCDebug(lcSharing) << "Received sharing permissions for" << _sharePath << _maxSharingPermissions; } showSharingUi(); @@ -208,7 +208,7 @@ void ShareDialog::showSharingUi() void ShareDialog::slotThumbnailFetched(const int &statusCode, const QByteArray &reply) { if (statusCode != 200) { - qDebug() << Q_FUNC_INFO << "Status code: " << statusCode; + qCDebug(lcSharing) << "Thumbnail status code: " << statusCode; return; } @@ -220,7 +220,7 @@ void ShareDialog::slotThumbnailFetched(const int &statusCode, const QByteArray & void ShareDialog::slotAccountStateChanged(int state) { bool enabled = (state == AccountState::State::Connected); - qDebug() << Q_FUNC_INFO << enabled; + qCDebug(lcSharing) << "Account connected?" << enabled; if (_userGroupWidget != NULL) { _userGroupWidget->setEnabled(enabled); diff --git a/src/gui/sharee.cpp b/src/gui/sharee.cpp index d7f79547d..1553a3069 100644 --- a/src/gui/sharee.cpp +++ b/src/gui/sharee.cpp @@ -21,6 +21,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcSharing, "gui.sharing", QtInfoMsg) + Sharee::Sharee(const QString shareWith, const QString displayName, const Type type) diff --git a/src/gui/sharee.h b/src/gui/sharee.h index 150126970..0391eae53 100644 --- a/src/gui/sharee.h +++ b/src/gui/sharee.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +31,8 @@ class QJsonObject; namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcSharing) + class Sharee { public: diff --git a/src/gui/sharelinkwidget.cpp b/src/gui/sharelinkwidget.cpp index 1195edb7f..4885fff5a 100644 --- a/src/gui/sharelinkwidget.cpp +++ b/src/gui/sharelinkwidget.cpp @@ -118,7 +118,7 @@ ShareLinkWidget::ShareLinkWidget(AccountPtr account, // // _ui->checkBox_shareLink->setEnabled(false); // uploadExternalFile(); - qDebug() << Q_FUNC_INFO << "Unable to share files not in a sync folder."; + qCDebug(lcSharing) << "Unable to share files not in a sync folder."; return; } @@ -181,7 +181,7 @@ void ShareLinkWidget::getShares() void ShareLinkWidget::slotSharesFetched(const QList> &shares) { const QString versionString = _account->serverVersion(); - qDebug() << Q_FUNC_INFO << versionString << "Fetched" << shares.count() << "shares"; + qCDebug(lcSharing) << versionString << "Fetched" << shares.count() << "shares"; // Preserve the previous selection QString selectedShareId; @@ -590,7 +590,7 @@ void ShareLinkWidget::slotServerError(int code, const QString &message) _pi_password->stopAnimation(); _pi_editing->stopAnimation(); - qDebug() << "Error from server" << code << message; + qCDebug(lcSharing) << "Error from server" << code << message; displayError(message); } diff --git a/src/gui/sharemanager.cpp b/src/gui/sharemanager.cpp index 3c532134d..3993430fd 100644 --- a/src/gui/sharemanager.cpp +++ b/src/gui/sharemanager.cpp @@ -352,7 +352,7 @@ void ShareManager::slotSharesFetched(const QJsonDocument &reply) { auto tmpShares = reply.object().value("ocs").toObject().value("data").toArray(); const QString versionString = _account->serverVersion(); - qDebug() << Q_FUNC_INFO << versionString << "Fetched" << tmpShares.count() << "shares"; + qCDebug(lcSharing) << versionString << "Fetched" << tmpShares.count() << "shares"; QList> shares; @@ -372,7 +372,7 @@ void ShareManager::slotSharesFetched(const QJsonDocument &reply) shares.append(QSharedPointer(newShare)); } - qDebug() << Q_FUNC_INFO << "Sending " << shares.count() << "shares"; + qCDebug(lcSharing) << "Sending " << shares.count() << "shares"; emit sharesFetched(shares); } diff --git a/src/gui/shareusergroupwidget.cpp b/src/gui/shareusergroupwidget.cpp index aef9f890d..45c9a4091 100644 --- a/src/gui/shareusergroupwidget.cpp +++ b/src/gui/shareusergroupwidget.cpp @@ -295,7 +295,7 @@ void ShareUserGroupWidget::displayError(int code, const QString& message) delete pi; } - qDebug() << "Error from server" << code << message; + qCDebug(lcSharing) << "Sharing error from server" << code << message; _ui->errorLabel->setText(message); _ui->errorLabel->show(); _ui->shareeLineEdit->setEnabled(true); diff --git a/src/gui/socketapi.cpp b/src/gui/socketapi.cpp index 361c7a34f..a2b9bb062 100644 --- a/src/gui/socketapi.cpp +++ b/src/gui/socketapi.cpp @@ -34,7 +34,6 @@ #include "asserts.h" #include -#include #include #include #include @@ -59,8 +58,6 @@ // The second number should be changed when there are new features. #define MIRALL_SOCKET_API_VERSION "1.0" -#define DEBUG qDebug() << "SocketApi: " - static inline QString removeTrailingSlash(QString path) { Q_ASSERT(path.endsWith(QLatin1Char('/'))); @@ -86,6 +83,8 @@ static QString buildMessage(const QString& verb, const QString &path, const QStr namespace OCC { +Q_LOGGING_CATEGORY(lcSocketApi, "gui.socketapi", QtInfoMsg) + class BloomFilter { // Initialize with m=1024 bits and k=2 (high and low 16 bits of a qHash). // For a client navigating in less than 100 directories, this gives us a probability less than (1-e^(-2*100/1024))^2 = 0.03147872136 false positives. @@ -115,7 +114,7 @@ public: void sendMessage(const QString& message, bool doWait = false) const { - DEBUG << "Sending message: " << message; + qCDebug(lcSocketApi) << "Sending message: " << message; QString localMessage = message; if( ! localMessage.endsWith(QLatin1Char('\n'))) { localMessage.append(QLatin1Char('\n')); @@ -127,7 +126,7 @@ public: socket->waitForBytesWritten(1000); } if( sent != bytesToSend.length() ) { - qDebug() << "WARN: Could not send all data on socket for " << localMessage; + qCDebug(lcSocketApi) << "WARN: Could not send all data on socket for " << localMessage; } } @@ -184,23 +183,23 @@ SocketApi::SocketApi(QObject* parent) #endif socketPath = runtimeDir + "/" + Theme::instance()->appName() + "/socket"; } else { - DEBUG << "An unexpected system detected"; + qCDebug(lcSocketApi) << "An unexpected system detected"; } SocketApiServer::removeServer(socketPath); QFileInfo info(socketPath); if (!info.dir().exists()) { bool result = info.dir().mkpath("."); - DEBUG << "creating" << info.dir().path() << result; + qCDebug(lcSocketApi) << "creating" << info.dir().path() << result; if( result ) { QFile::setPermissions(socketPath, QFile::Permissions(QFile::ReadOwner+QFile::WriteOwner+QFile::ExeOwner)); } } if(!_localServer.listen(socketPath)) { - DEBUG << "can't start server" << socketPath; + qCDebug(lcSocketApi) << "can't start server" << socketPath; } else { - DEBUG << "server started, listening at " << socketPath; + qCDebug(lcSocketApi) << "server started, listening at " << socketPath; } connect(&_localServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection())); @@ -211,7 +210,7 @@ SocketApi::SocketApi(QObject* parent) SocketApi::~SocketApi() { - DEBUG << "dtor"; + qCDebug(lcSocketApi) << "dtor"; _localServer.close(); // All remaining sockets will be destroyed with _localServer, their parent ASSERT(_listeners.isEmpty() || _listeners.first().socket->parent() == &_localServer); @@ -225,7 +224,7 @@ void SocketApi::slotNewConnection() if( ! socket ) { return; } - DEBUG << "New connection" << socket; + qCDebug(lcSocketApi) << "New connection" << socket; connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadSocket())); connect(socket, SIGNAL(disconnected()), this, SLOT(onLostConnection())); connect(socket, SIGNAL(destroyed(QObject*)), this, SLOT(slotSocketDestroyed(QObject*))); @@ -244,7 +243,7 @@ void SocketApi::slotNewConnection() void SocketApi::onLostConnection() { - DEBUG << "Lost connection " << sender(); + qCDebug(lcSocketApi) << "Lost connection " << sender(); sender()->deleteLater(); } @@ -273,7 +272,7 @@ void SocketApi::slotReadSocket() if(indexOfMethod != -1) { staticMetaObject.method(indexOfMethod).invoke(this, Q_ARG(QString, argument), Q_ARG(SocketListener*, listener)); } else { - DEBUG << "The command is not supported by this version of the client:" << command << "with argument:" << argument; + qCDebug(lcSocketApi) << "The command is not supported by this version of the client:" << command << "with argument:" << argument; } } } @@ -327,7 +326,7 @@ void SocketApi::slotUpdateFolderView(Folder *f) broadcastMessage(buildMessage(QLatin1String("UPDATE_VIEW"), rootPath)); } else { - qDebug() << "Not sending UPDATE_VIEW for" << f->alias() << "because status() is" << f->syncResult().status(); + qCDebug(lcSocketApi) << "Not sending UPDATE_VIEW for" << f->alias() << "because status() is" << f->syncResult().status(); } } } @@ -352,14 +351,12 @@ void SocketApi::broadcastStatusPushMessage(const QString& systemPath, SyncFileSt void SocketApi::command_RETRIEVE_FOLDER_STATUS(const QString& argument, SocketListener* listener) { // This command is the same as RETRIEVE_FILE_STATUS - - //qDebug() << Q_FUNC_INFO << argument; command_RETRIEVE_FILE_STATUS(argument, listener); } void SocketApi::command_RETRIEVE_FILE_STATUS(const QString& argument, SocketListener* listener) { - qDebug() << Q_FUNC_INFO << argument; + qCDebug(lcSocketApi) << argument; QString statusString; @@ -371,7 +368,7 @@ void SocketApi::command_RETRIEVE_FILE_STATUS(const QString& argument, SocketList QString systemPath = QDir::cleanPath(argument); if( systemPath.endsWith(QLatin1Char('/')) ) { systemPath.truncate(systemPath.length()-1); - qWarning() << "Removed trailing slash for directory: " << systemPath << "Status pushes won't have one."; + qCWarning(lcSocketApi) << "Removed trailing slash for directory: " << systemPath << "Status pushes won't have one."; } // The user probably visited this directory in the file shell. // Let the listener know that it should now send status pushes for sibblings of this file. @@ -389,7 +386,7 @@ void SocketApi::command_RETRIEVE_FILE_STATUS(const QString& argument, SocketList void SocketApi::command_SHARE(const QString& localFile, SocketListener* listener) { - qDebug() << Q_FUNC_INFO << localFile; + qCDebug(lcSocketApi) << localFile; auto theme = Theme::instance(); @@ -451,7 +448,7 @@ void SocketApi::command_VERSION(const QString&, SocketListener* listener) void SocketApi::command_SHARE_STATUS(const QString &localFile, SocketListener* listener) { - qDebug() << Q_FUNC_INFO << localFile; + qCDebug(lcSocketApi) << localFile; Folder *shareFolder = FolderMan::instance()->folderForPath(localFile); diff --git a/src/gui/sslbutton.cpp b/src/gui/sslbutton.cpp index d9a65c360..a36747e7c 100644 --- a/src/gui/sslbutton.cpp +++ b/src/gui/sslbutton.cpp @@ -27,6 +27,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcSsl, "gui.ssl", QtInfoMsg) + SslButton::SslButton(QWidget *parent) : QToolButton(parent) { @@ -227,7 +229,7 @@ void SslButton::slotUpdateMenu() { QList chain = account->_peerCertificateChain; if (chain.isEmpty()) { - qWarning() << "empty certificate chain"; + qCWarning(lcSsl) << "Empty certificate chain"; return; } diff --git a/src/gui/sslerrordialog.cpp b/src/gui/sslerrordialog.cpp index 21a420691..8c7676b7b 100644 --- a/src/gui/sslerrordialog.cpp +++ b/src/gui/sslerrordialog.cpp @@ -27,6 +27,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcSslErrorDialog, "gui.sslerrordialog", QtInfoMsg) + #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) namespace Utility { // Used for QSSLCertificate::subjectInfo which returns a QStringList in Qt5, but a QString in Qt4 @@ -38,7 +40,7 @@ bool SslDialogErrorHandler::handleErrors(QList errors, const QSslConf { (void) conf; if (!certs) { - qDebug() << "Certs parameter required but is NULL!"; + qCDebug(lcSslErrorDialog) << "Certs parameter required but is NULL!"; return false; } @@ -151,8 +153,6 @@ bool SslErrorDialog::checkFailingCertsKnown( const QList &errors ) } msg += QL(""); - //qDebug() << "# # # # # # "; - //qDebug() << msg; QTextDocument *doc = new QTextDocument(0); QString style = styleSheet(); doc->addResource( QTextDocument::StyleSheetResource, QUrl( QL("format.css") ), style); @@ -214,7 +214,7 @@ bool SslErrorDialog::trustConnection() if( _allTrusted ) return true; bool stat = ( _ui->_cbTrustConnect->checkState() == Qt::Checked ); - qDebug() << "SSL-Connection is trusted: " << stat; + qCDebug(lcSslErrorDialog) << "SSL-Connection is trusted: " << stat; return stat; } diff --git a/src/gui/systray.cpp b/src/gui/systray.cpp index 57d74e061..e1e72cb06 100644 --- a/src/gui/systray.cpp +++ b/src/gui/systray.cpp @@ -14,7 +14,6 @@ #include "systray.h" #include "theme.h" -#include #ifdef USE_FDO_NOTIFICATIONS #include diff --git a/src/gui/systray.mm b/src/gui/systray.mm index ea30a3864..95e0a11a7 100644 --- a/src/gui/systray.mm +++ b/src/gui/systray.mm @@ -1,5 +1,4 @@ #include -#include #import @interface NotificationCenterDelegate : NSObject @@ -24,7 +23,6 @@ bool canOsXSendUserNotification() void sendOsXUserNotification(const QString &title, const QString &message) { - qDebug() << Q_FUNC_INFO << title << message; Class cuserNotificationCenter = NSClassFromString(@"NSUserNotificationCenter"); id userNotificationCenter = [cuserNotificationCenter defaultUserNotificationCenter]; diff --git a/src/gui/tooltipupdater.cpp b/src/gui/tooltipupdater.cpp index a8136731c..0f9b0510a 100644 --- a/src/gui/tooltipupdater.cpp +++ b/src/gui/tooltipupdater.cpp @@ -17,7 +17,6 @@ #include #include #include -#include using namespace OCC; diff --git a/src/gui/updater/ocupdater.cpp b/src/gui/updater/ocupdater.cpp index 18a4cf53c..2fd27fa0e 100644 --- a/src/gui/updater/ocupdater.cpp +++ b/src/gui/updater/ocupdater.cpp @@ -67,12 +67,12 @@ void UpdaterScheduler::slotTimerFired() auto checkInterval = cfg.updateCheckInterval(); if( checkInterval != _updateCheckTimer.interval() ) { _updateCheckTimer.setInterval(checkInterval); - qDebug() << "Setting new update check interval " << checkInterval; + qCDebug(lcUpdater) << "Setting new update check interval " << checkInterval; } // consider the skipUpdateCheck flag in the config. if( cfg.skipUpdateCheck() ) { - qDebug() << Q_FUNC_INFO << "Skipping update check because of config file"; + qCDebug(lcUpdater) << "Skipping update check because of config file"; return; } @@ -123,14 +123,14 @@ void OCUpdater::backgroundCheckForUpdate() case UpToDate: case DownloadFailed: case DownloadTimedOut: - qDebug() << Q_FUNC_INFO << "checking for available update"; + qCDebug(lcUpdater) << "checking for available update"; checkForUpdate(); break; case DownloadComplete: - qDebug() << "Update is downloaded, skip new check."; + qCDebug(lcUpdater) << "Update is downloaded, skip new check."; break; case UpdateOnlyAvailableThroughSystem: - qDebug() << "Update is only available through system, skip check."; + qCDebug(lcUpdater) << "Update is only available through system, skip check."; break; } } @@ -188,7 +188,7 @@ void OCUpdater::slotStartInstaller() QString updateFile = settings.value(updateAvailableC).toString(); settings.setValue(autoUpdateAttemptedC, true); settings.sync(); - qDebug() << "Running updater" << updateFile; + qCDebug(lcUpdater) << "Running updater" << updateFile; QProcess::startDetached(updateFile, QStringList() << "/S" << "/launch"); } @@ -223,7 +223,7 @@ void OCUpdater::slotVersionInfoArrived() QNetworkReply *reply = qobject_cast(sender()); reply->deleteLater(); if( reply->error() != QNetworkReply::NoError ) { - qDebug() << "Failed to reach version check url: " << reply->errorString(); + qCDebug(lcUpdater) << "Failed to reach version check url: " << reply->errorString(); return; } @@ -234,7 +234,7 @@ void OCUpdater::slotVersionInfoArrived() if( ok ) { versionInfoArrived(_updateInfo); } else { - qDebug() << "Could not parse update information."; + qCDebug(lcUpdater) << "Could not parse update information."; } } @@ -272,7 +272,7 @@ void NSISUpdater::slotDownloadFinished() _file->close(); QFile::copy(_file->fileName(), _targetFile); setDownloadState(DownloadComplete); - qDebug() << "Downloaded" << url.toString() << "to" << _targetFile; + qCDebug(lcUpdater) << "Downloaded" << url.toString() << "to" << _targetFile; ConfigFile cfg; QSettings settings(cfg.configFile(), QSettings::IniFormat); settings.setValue(updateTargetVersionC, updateInfo().version()); @@ -290,7 +290,7 @@ void NSISUpdater::versionInfoArrived(const UpdateInfo &info) || infoVersion <= currVersion || infoVersion <= seenVersion) { - qDebug() << "Client is on latest version!"; + qCDebug(lcUpdater) << "Client is on latest version!"; setDownloadState(UpToDate); } else { QString url = info.downloadUrl(); @@ -442,7 +442,6 @@ void PassiveUpdateNotifier::backgroundCheckForUpdate() // on linux, check if the installed binary is still the same version // as the one that is running. If not, restart if possible. const QByteArray fsVersion = Utility::versionOfInstalledBinary(); - qDebug() << Q_FUNC_INFO; if( !(fsVersion.isEmpty() || _runningAppVersion.isEmpty()) && fsVersion != _runningAppVersion ) { emit requestRestart(); } @@ -458,7 +457,7 @@ void PassiveUpdateNotifier::versionInfoArrived(const UpdateInfo &info) if( info.version().isEmpty() || currentVer >= remoteVer ) { - qDebug() << "Client is on latest version!"; + qCDebug(lcUpdater) << "Client is on latest version!"; setDownloadState(UpToDate); } else { setDownloadState(UpdateOnlyAvailableThroughSystem); diff --git a/src/gui/updater/sparkleupdater_mac.mm b/src/gui/updater/sparkleupdater_mac.mm index b117026fc..61ac289cc 100644 --- a/src/gui/updater/sparkleupdater_mac.mm +++ b/src/gui/updater/sparkleupdater_mac.mm @@ -22,8 +22,6 @@ #include "utility.h" -#include - // Does not work yet @interface DelegateObject : NSObject - (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle; @@ -33,38 +31,33 @@ // Only possible in later versions, we're not up to date here. - (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle { - qDebug() << Q_FUNC_INFO << "may check: YES"; + qCDebug(lcUpdater) << "may check: YES"; return YES; } // Sent when a valid update is found by the update driver. - (void)updater:(SUUpdater *)updater didFindValidUpdate:(SUAppcastItem *)update { - qDebug() << Q_FUNC_INFO; } // Sent when a valid update is not found. // Does not seem to get called ever. - (void)updaterDidNotFindUpdate:(SUUpdater *)update { - qDebug() << Q_FUNC_INFO; } // Sent immediately before installing the specified update. - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update { - qDebug() << Q_FUNC_INFO; } // Tried implementing those methods, but they never ever seem to get called //- (void) updater:(SUUpdater *)updater didAbortWithError:(NSError *)error //{ -// qDebug() << Q_FUNC_INFO << [error localizedDescription]; //} //- (void)updater:(SUUpdater *)updater didFinishLoadingAppcast:(SUAppcast *)appcast //{ -// qDebug() << Q_FUNC_INFO << appcast; //} @@ -121,7 +114,7 @@ bool autoUpdaterAllowed() if ([expectedPath isEqualTo:bundlePath]) { return true; } - qDebug() << "ERROR: We are not in /Applications, won't check for update!"; + qCDebug(lcUpdater) << "ERROR: We are not in /Applications, won't check for update!"; return false; } @@ -135,7 +128,7 @@ void SparkleUpdater::checkForUpdate() void SparkleUpdater::backgroundCheckForUpdate() { - qDebug() << Q_FUNC_INFO << "launching background check"; + qCDebug(lcUpdater) << "launching background check"; if (autoUpdaterAllowed()) { [d->updater checkForUpdatesInBackground]; } diff --git a/src/gui/updater/updateinfo.cpp b/src/gui/updater/updateinfo.cpp index 902df9209..225cdb69f 100644 --- a/src/gui/updater/updateinfo.cpp +++ b/src/gui/updater/updateinfo.cpp @@ -2,6 +2,7 @@ // All changes you do to this file will be lost. #include "updateinfo.h" +#include "updater.h" #include #include @@ -54,7 +55,7 @@ QString UpdateInfo::downloadUrl() const UpdateInfo UpdateInfo::parseElement( const QDomElement &element, bool *ok ) { if ( element.tagName() != QLatin1String("owncloudclient") ) { - qCritical() << "Expected 'owncloudclient', got '" << element.tagName() << "'."; + qCCritical(lcUpdater) << "Expected 'owncloudclient', got '" << element.tagName() << "'."; if ( ok ) *ok = false; return UpdateInfo(); } @@ -105,7 +106,7 @@ UpdateInfo UpdateInfo::parseFile( const QString &filename, bool *ok ) { QFile file( filename ); if ( !file.open( QIODevice::ReadOnly ) ) { - qCritical() << "Unable to open file '" << filename << "'"; + qCCritical(lcUpdater) << "Unable to open file '" << filename << "'"; if ( ok ) *ok = false; return UpdateInfo(); } @@ -114,7 +115,7 @@ UpdateInfo UpdateInfo::parseFile( const QString &filename, bool *ok ) int errorLine, errorCol; QDomDocument doc; if ( !doc.setContent( &file, false, &errorMsg, &errorLine, &errorCol ) ) { - qCritical() << errorMsg << " at " << errorLine << "," << errorCol; + qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol; if ( ok ) *ok = false; return UpdateInfo(); } @@ -133,7 +134,7 @@ UpdateInfo UpdateInfo::parseString( const QString &xml, bool *ok ) int errorLine, errorCol; QDomDocument doc; if ( !doc.setContent( xml, false, &errorMsg, &errorLine, &errorCol ) ) { - qCritical() << errorMsg << " at " << errorLine << "," << errorCol; + qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol; if ( ok ) *ok = false; return UpdateInfo(); } @@ -150,7 +151,7 @@ bool UpdateInfo::writeFile( const QString &filename ) { QFile file( filename ); if ( !file.open( QIODevice::WriteOnly ) ) { - qCritical() << "Unable to open file '" << filename << "'"; + qCCritical(lcUpdater) << "Unable to open file '" << filename << "'"; return false; } diff --git a/src/gui/updater/updater.cpp b/src/gui/updater/updater.cpp index 96533db59..a6bdd82d7 100644 --- a/src/gui/updater/updater.cpp +++ b/src/gui/updater/updater.cpp @@ -14,7 +14,6 @@ #include #include -#include #include "updater/updater.h" #include "updater/sparkleupdater.h" @@ -28,6 +27,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcUpdater, "gui.updater", QtInfoMsg) + Updater *Updater::_instance = 0; Updater * Updater::instance() @@ -71,7 +72,7 @@ QString Updater::getSystemInfo() process.start( QLatin1String("lsb_release -a") ); process.waitForFinished(); QByteArray output = process.readAllStandardOutput(); - qDebug() << "Sys Info size: " << output.length(); + qCDebug(lcUpdater) << "Sys Info size: " << output.length(); if( output.length() > 1024 ) output.clear(); // don't send too much. return QString::fromLocal8Bit( output.toBase64() ); @@ -88,7 +89,7 @@ Updater *Updater::create() updateBaseUrl = QUrl(QLatin1String(APPLICATION_UPDATE_URL)); } if (!updateBaseUrl.isValid() || updateBaseUrl.host() == ".") { - qDebug() << "Not a valid updater URL, will not do update check"; + qCDebug(lcUpdater) << "Not a valid updater URL, will not do update check"; return 0; } updateBaseUrl = addQueryParams(updateBaseUrl); diff --git a/src/gui/updater/updater.h b/src/gui/updater/updater.h index 8af3c6c19..07c6528bf 100644 --- a/src/gui/updater/updater.h +++ b/src/gui/updater/updater.h @@ -15,12 +15,15 @@ #ifndef UPDATER_H #define UPDATER_H +#include #include class QUrl; namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcUpdater) + class Updater : public QObject { Q_OBJECT public: diff --git a/src/gui/wizard/owncloudwizard.cpp b/src/gui/wizard/owncloudwizard.cpp index 961763dc1..b5032bbc0 100644 --- a/src/gui/wizard/owncloudwizard.cpp +++ b/src/gui/wizard/owncloudwizard.cpp @@ -36,6 +36,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcWizard, "gui.wizard", QtInfoMsg) + OwncloudWizard::OwncloudWizard(QWidget *parent) : QWizard(parent), _account(0), @@ -151,7 +153,7 @@ void OwncloudWizard::successfulStep() case WizardCommon::Page_ServerSetup: case WizardCommon::Page_Result: - qWarning("Should not happen at this stage."); + qCWarning(lcWizard, "Should not happen at this stage."); break; } @@ -175,7 +177,7 @@ void OwncloudWizard::setAuthType(WizardCommon::AuthType type) // TODO: update this function void OwncloudWizard::slotCurrentPageChanged( int id ) { - qDebug() << "Current Wizard page changed to " << id; + qCDebug(lcWizard) << "Current Wizard page changed to " << id; if( id == WizardCommon::Page_ServerSetup ) { emit clearPendingRequests(); @@ -212,7 +214,7 @@ void OwncloudWizard::displayError( const QString& msg, bool retryHTTPonly ) void OwncloudWizard::appendToConfigurationLog( const QString& msg, LogType /*type*/ ) { _setupLog << msg; - qDebug() << "Setup-Log: " << msg; + qCDebug(lcWizard) << "Setup-Log: " << msg; } void OwncloudWizard::setOCUrl( const QString& url ) diff --git a/src/gui/wizard/owncloudwizard.h b/src/gui/wizard/owncloudwizard.h index ecb5510ab..93391a2b5 100644 --- a/src/gui/wizard/owncloudwizard.h +++ b/src/gui/wizard/owncloudwizard.h @@ -17,6 +17,7 @@ #define MIRALL_OWNCLOUD_WIZARD_H #include +#include #include #include @@ -25,6 +26,8 @@ namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcWizard) + class OwncloudSetupPage; class OwncloudHttpCredsPage; #ifndef NO_SHIBBOLETH diff --git a/src/gui/wizard/owncloudwizardresultpage.cpp b/src/gui/wizard/owncloudwizardresultpage.cpp index 4018fedba..891417387 100644 --- a/src/gui/wizard/owncloudwizardresultpage.cpp +++ b/src/gui/wizard/owncloudwizardresultpage.cpp @@ -13,7 +13,6 @@ * for more details. */ -#include #include #include #include @@ -99,7 +98,6 @@ void OwncloudWizardResultPage::slotOpenServer() { Theme* theme = Theme::instance(); QUrl url = QUrl(field("OCUrl").toString() + theme->wizardUrlPostfix()); - qDebug() << Q_FUNC_INFO << url; QDesktopServices::openUrl(url); } diff --git a/src/gui/wizard/postfixlineedit.cpp b/src/gui/wizard/postfixlineedit.cpp index 6ed14ec2f..5e4171c32 100644 --- a/src/gui/wizard/postfixlineedit.cpp +++ b/src/gui/wizard/postfixlineedit.cpp @@ -15,8 +15,6 @@ #include #include -#include - #include "postfixlineedit.h" namespace OCC { @@ -54,7 +52,6 @@ void PostfixLineEdit::setFullText(const QString &text) if (prefixString.endsWith(postfix())) { prefixString.chop(postfix().length()); } - qDebug() << prefixString; setText(prefixString); } diff --git a/src/libsync/abstractnetworkjob.cpp b/src/libsync/abstractnetworkjob.cpp index fcb7689dd..26f33c9cd 100644 --- a/src/libsync/abstractnetworkjob.cpp +++ b/src/libsync/abstractnetworkjob.cpp @@ -13,6 +13,7 @@ * for more details. */ +#include #include #include #include @@ -24,7 +25,6 @@ #include #include #include -#include #include #include "networkjobs.h" @@ -37,6 +37,7 @@ Q_DECLARE_METATYPE(QTimer*) namespace OCC { +Q_LOGGING_CATEGORY(lcNetworkJob, "sync.networkjob", QtInfoMsg) AbstractNetworkJob::AbstractNetworkJob(AccountPtr account, const QString &path, QObject *parent) : QObject(parent) @@ -74,8 +75,6 @@ void AbstractNetworkJob::setReply(QNetworkReply *reply) void AbstractNetworkJob::setTimeout(qint64 msec) { - //qDebug() << Q_FUNC_INFO << msec; - _timer.start(msec); } @@ -149,14 +148,14 @@ void AbstractNetworkJob::slotFinished() _timer.stop(); if( _reply->error() == QNetworkReply::SslHandshakeFailedError ) { - qDebug() << "SslHandshakeFailedError: " << errorString() << " : can be caused by a webserver wanting SSL client certificates"; + qCDebug(lcNetworkJob) << "SslHandshakeFailedError: " << errorString() << " : can be caused by a webserver wanting SSL client certificates"; } if( _reply->error() != QNetworkReply::NoError ) { - qDebug() << Q_FUNC_INFO << _reply->error() << errorString() + qCDebug(lcNetworkJob) << _reply->error() << errorString() << _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if (_reply->error() == QNetworkReply::ProxyAuthenticationRequiredError) { - qDebug() << Q_FUNC_INFO << _reply->rawHeader("Proxy-Authenticate"); + qCDebug(lcNetworkJob) << _reply->rawHeader("Proxy-Authenticate"); } emit networkError(_reply); } @@ -174,16 +173,16 @@ void AbstractNetworkJob::slotFinished() QByteArray verb = requestVerb(*reply()); if (requestedUrl.scheme() == QLatin1String("https") && redirectUrl.scheme() == QLatin1String("http")) { - qWarning() << this << "HTTPS->HTTP downgrade detected!"; + qCWarning(lcNetworkJob) << this << "HTTPS->HTTP downgrade detected!"; } else if (requestedUrl == redirectUrl || _redirectCount >= maxRedirects()) { - qWarning() << this << "Redirect loop detected!"; + qCWarning(lcNetworkJob) << this << "Redirect loop detected!"; } else if (_requestBody && _requestBody->isSequential()) { - qWarning() << this << "cannot redirect request with sequential body"; + qCWarning(lcNetworkJob) << this << "cannot redirect request with sequential body"; } else if (verb.isEmpty()) { - qWarning() << this << "cannot redirect request: could not detect original verb"; + qCWarning(lcNetworkJob) << this << "cannot redirect request: could not detect original verb"; } else { // Create the redirected request and send it - qDebug() << "Redirecting" << verb << requestedUrl << redirectUrl; + qCDebug(lcNetworkJob) << "Redirecting" << verb << requestedUrl << redirectUrl; resetTimeout(); if (_requestBody) { _requestBody->seek(0); @@ -260,13 +259,13 @@ void AbstractNetworkJob::start() const QString displayUrl = QString( "%1://%2%3").arg(url.scheme()).arg(url.host()).arg(url.path()); QString parentMetaObjectName = parent() ? parent()->metaObject()->className() : ""; - qDebug() << "!!!" << metaObject()->className() << "created for" << displayUrl << "+" << path() << parentMetaObjectName; + qCDebug(lcNetworkJob) << metaObject()->className() << "created for" << displayUrl << "+" << path() << parentMetaObjectName; } void AbstractNetworkJob::slotTimeout() { _timedout = true; - qDebug() << this << "Timeout" << (reply() ? reply()->request().url() : path()); + qCDebug(lcNetworkJob) << this << "Timeout" << (reply() ? reply()->request().url() : path()); onTimedOut(); } diff --git a/src/libsync/accessmanager.cpp b/src/libsync/accessmanager.cpp index fe4258a03..62e403808 100644 --- a/src/libsync/accessmanager.cpp +++ b/src/libsync/accessmanager.cpp @@ -12,6 +12,7 @@ * for more details. */ +#include #include #include #include @@ -28,6 +29,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcAccessManager, "sync.accessmanager", QtInfoMsg) + AccessManager::AccessManager(QObject* parent) : QNetworkAccessManager (parent) { @@ -49,7 +52,7 @@ void AccessManager::setRawCookie(const QByteArray &rawCookie, const QUrl &url) { QNetworkCookie cookie(rawCookie.left(rawCookie.indexOf('=')), rawCookie.mid(rawCookie.indexOf('=')+1)); - qDebug() << Q_FUNC_INFO << cookie.name() << cookie.value(); + qCDebug(lcAccessManager) << cookie.name() << cookie.value(); QList cookieList; cookieList.append(cookie); diff --git a/src/libsync/account.cpp b/src/libsync/account.cpp index 21c31e2d0..273ca24c4 100644 --- a/src/libsync/account.cpp +++ b/src/libsync/account.cpp @@ -23,6 +23,7 @@ #include "asserts.h" #include +#include #include #include #include @@ -30,11 +31,11 @@ #include #include #include -#include #include namespace OCC { +Q_LOGGING_CATEGORY(lcAccount, "sync.account", QtInfoMsg) Account::Account(QObject *parent) : QObject(parent) @@ -193,7 +194,7 @@ void Account::resetNetworkAccessManager() return; } - qDebug() << "Resetting QNAM"; + qCDebug(lcAccount) << "Resetting QNAM"; QNetworkCookieJar* jar = _am->cookieJar(); // Use a QSharedPointer to allow locking the life of the QNAM on the stack. @@ -327,13 +328,13 @@ void Account::slotHandleSslErrors(QNetworkReply *reply , QList errors // If all certs have previously been rejected by the user, don't ask again. if( allPreviouslyRejected ) { - qDebug() << out << "Certs not trusted by user decision, returning."; + qCDebug(lcAccount) << out << "Certs not trusted by user decision, returning."; return; } QList approvedCerts; if (_sslErrorHandler.isNull() ) { - qDebug() << out << Q_FUNC_INFO << "called without valid SSL error handler for account" << url(); + qCDebug(lcAccount) << out << "called without valid SSL error handler for account" << url(); return; } @@ -351,7 +352,7 @@ void Account::slotHandleSslErrors(QNetworkReply *reply , QList errors addApprovedCerts(approvedCerts); emit wantsAccountSaved(this); // all ssl certs are known and accepted. We can ignore the problems right away. -// qDebug() << out << "Certs are known and trusted! This is not an actual error."; + qCDebug(lcAccount) << out << "Certs are known and trusted! This is not an actual error."; // Warning: Do *not* use ignoreSslErrors() (without args) here: // it permanently ignores all SSL errors for this host, even diff --git a/src/libsync/bandwidthmanager.cpp b/src/libsync/bandwidthmanager.cpp index e3f25c089..8b85be4ed 100644 --- a/src/libsync/bandwidthmanager.cpp +++ b/src/libsync/bandwidthmanager.cpp @@ -23,11 +23,14 @@ #include #endif +#include #include #include namespace OCC { +Q_LOGGING_CATEGORY(lcBandwidthManager, "sync.bandwidthmanager", QtInfoMsg) + // Because of the many layers of buffering inside Qt (and probably the OS and the network) // we cannot lower this value much more. If we do, the estimated bw will be very high // because the buffers fill fast while the actual network algorithms are not relevant yet. @@ -85,12 +88,10 @@ BandwidthManager::BandwidthManager(OwncloudPropagator *p) : QObject(), BandwidthManager::~BandwidthManager() { - qDebug() << Q_FUNC_INFO; } void BandwidthManager::registerUploadDevice(UploadDevice *p) { - //qDebug() << Q_FUNC_INFO << p; _absoluteUploadDeviceList.append(p); _relativeUploadDeviceList.append(p); QObject::connect(p, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterUploadDevice(QObject*))); @@ -117,7 +118,6 @@ void BandwidthManager::unregisterUploadDevice(QObject *o) void BandwidthManager::unregisterUploadDevice(UploadDevice* p) { - //qDebug() << Q_FUNC_INFO << p; _absoluteUploadDeviceList.removeAll(p); _relativeUploadDeviceList.removeAll(p); if (p == _relativeLimitCurrentMeasuredDevice) { @@ -128,7 +128,6 @@ void BandwidthManager::unregisterUploadDevice(UploadDevice* p) void BandwidthManager::registerDownloadJob(GETFileJob* j) { - //qDebug() << Q_FUNC_INFO << j; _downloadJobList.append(j); QObject::connect(j, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterDownloadJob(QObject*))); @@ -170,25 +169,25 @@ void BandwidthManager::relativeUploadMeasuringTimerExpired() return; } if (_relativeLimitCurrentMeasuredDevice == 0) { - qDebug() << Q_FUNC_INFO << "No device set, just waiting 1 sec"; + qCDebug(lcBandwidthManager) << "No device set, just waiting 1 sec"; _relativeUploadDelayTimer.setInterval(1000); _relativeUploadDelayTimer.start(); return; } -// qDebug() << Q_FUNC_INFO << _relativeUploadDeviceList.count() << "Starting Delay"; + qCDebug(lcBandwidthManager) << _relativeUploadDeviceList.count() << "Starting Delay"; qint64 relativeLimitProgressMeasured = (_relativeLimitCurrentMeasuredDevice->_readWithProgress + _relativeLimitCurrentMeasuredDevice->_read) / 2; qint64 relativeLimitProgressDifference = relativeLimitProgressMeasured - _relativeUploadLimitProgressAtMeasuringRestart; -// qDebug() << Q_FUNC_INFO << _relativeUploadLimitProgressAtMeasuringRestart -// << relativeLimitProgressMeasured << relativeLimitProgressDifference; + qCDebug(lcBandwidthManager) << _relativeUploadLimitProgressAtMeasuringRestart + << relativeLimitProgressMeasured << relativeLimitProgressDifference; -// qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0; -// qDebug() << Q_FUNC_INFO << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed (" -// << _relativeLimitCurrentMeasuredDevice->_readWithProgress << _relativeLimitCurrentMeasuredDevice->_read -// << qAbs(_relativeLimitCurrentMeasuredDevice->_readWithProgress -// - _relativeLimitCurrentMeasuredDevice->_read) << ")"; + qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0; + qCDebug(lcBandwidthManager) << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed (" + << _relativeLimitCurrentMeasuredDevice->_readWithProgress << _relativeLimitCurrentMeasuredDevice->_read + << qAbs(_relativeLimitCurrentMeasuredDevice->_readWithProgress + - _relativeLimitCurrentMeasuredDevice->_read) << ")"; qint64 uploadLimitPercent = -_currentUploadLimit; // don't use too extreme values @@ -197,9 +196,8 @@ void BandwidthManager::relativeUploadMeasuringTimerExpired() qint64 wholeTimeMsec = (100.0 / uploadLimitPercent) * relativeLimitMeasuringTimerIntervalMsec; qint64 waitTimeMsec = wholeTimeMsec - relativeLimitMeasuringTimerIntervalMsec; qint64 realWaitTimeMsec = waitTimeMsec + wholeTimeMsec; -// qDebug() << Q_FUNC_INFO << waitTimeMsec << " - "<< realWaitTimeMsec << -// " msec for " << uploadLimitPercent << "%"; -// qDebug() << Q_FUNC_INFO << "XXXX" << uploadLimitPercent << relativeLimitMeasuringTimerIntervalMsec; + qCDebug(lcBandwidthManager) << waitTimeMsec << " - "<< realWaitTimeMsec << + " msec for " << uploadLimitPercent << "%"; // We want to wait twice as long since we want to give all // devices the same quota we used now since we don't want @@ -209,12 +207,11 @@ void BandwidthManager::relativeUploadMeasuringTimerExpired() int deviceCount = _relativeUploadDeviceList.count(); qint64 quotaPerDevice = relativeLimitProgressDifference * (uploadLimitPercent / 100.0) / deviceCount + 1.0; -// qDebug() << Q_FUNC_INFO << "YYYY" << relativeLimitProgressDifference << uploadLimitPercent << deviceCount; Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) { ud->setBandwidthLimited(true); ud->setChoked(false); ud->giveBandwidthQuota(quotaPerDevice); -// qDebug() << Q_FUNC_INFO << "Gave" << quotaPerDevice/1024.0 << "kB to" << ud; + qCDebug(lcBandwidthManager) << "Gave" << quotaPerDevice/1024.0 << "kB to" << ud; } _relativeLimitCurrentMeasuredDevice = 0; } @@ -232,7 +229,7 @@ void BandwidthManager::relativeUploadDelayTimerExpired() return; } -// qDebug() << Q_FUNC_INFO << _relativeUploadDeviceList.count() << "Starting measuring"; + qCDebug(lcBandwidthManager) << _relativeUploadDeviceList.count() << "Starting measuring"; // Take first device and then append it again (= we round robin all devices) _relativeLimitCurrentMeasuredDevice = _relativeUploadDeviceList.takeFirst(); @@ -264,22 +261,22 @@ void BandwidthManager::relativeDownloadMeasuringTimerExpired() return; } if (_relativeLimitCurrentMeasuredJob == 0) { - qDebug() << Q_FUNC_INFO << "No job set, just waiting 1 sec"; + qCDebug(lcBandwidthManager) << "No job set, just waiting 1 sec"; _relativeDownloadDelayTimer.setInterval(1000); _relativeDownloadDelayTimer.start(); return; } -// qDebug() << Q_FUNC_INFO << _downloadJobList.count() << "Starting Delay"; + qCDebug(lcBandwidthManager) << _downloadJobList.count() << "Starting Delay"; qint64 relativeLimitProgressMeasured = _relativeLimitCurrentMeasuredJob->currentDownloadPosition(); qint64 relativeLimitProgressDifference = relativeLimitProgressMeasured - _relativeDownloadLimitProgressAtMeasuringRestart; - qDebug() << Q_FUNC_INFO << _relativeDownloadLimitProgressAtMeasuringRestart + qCDebug(lcBandwidthManager) << _relativeDownloadLimitProgressAtMeasuringRestart << relativeLimitProgressMeasured << relativeLimitProgressDifference; -// qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0; -// qDebug() << Q_FUNC_INFO << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed (" -// << _relativeLimitCurrentMeasuredJob->currentDownloadPosition() ; + qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0; + qCDebug(lcBandwidthManager) << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed (" + << _relativeLimitCurrentMeasuredJob->currentDownloadPosition() ; qint64 downloadLimitPercent = -_currentDownloadLimit; // don't use too extreme values @@ -288,9 +285,8 @@ void BandwidthManager::relativeDownloadMeasuringTimerExpired() qint64 wholeTimeMsec = (100.0 / downloadLimitPercent) * relativeLimitMeasuringTimerIntervalMsec; qint64 waitTimeMsec = wholeTimeMsec - relativeLimitMeasuringTimerIntervalMsec; qint64 realWaitTimeMsec = waitTimeMsec + wholeTimeMsec; -// qDebug() << Q_FUNC_INFO << waitTimeMsec << " - "<< realWaitTimeMsec << -// " msec for " << downloadLimitPercent << "%"; -// qDebug() << Q_FUNC_INFO << "XXXX" << downloadLimitPercent << relativeLimitMeasuringTimerIntervalMsec; + qCDebug(lcBandwidthManager) << waitTimeMsec << " - "<< realWaitTimeMsec << + " msec for " << downloadLimitPercent << "%"; // We want to wait twice as long since we want to give all // devices the same quota we used now since we don't want @@ -300,17 +296,16 @@ void BandwidthManager::relativeDownloadMeasuringTimerExpired() int jobCount = _downloadJobList.count(); qint64 quota = relativeLimitProgressDifference * (downloadLimitPercent / 100.0); -// if (quota > 20*1024) { -// qDebug() << "======== ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20*1024; -// quota -= 20*1024; -// } + if (quota > 20*1024) { + qCDebug(lcBandwidthManager) << "======== ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20*1024; + quota -= 20*1024; + } qint64 quotaPerJob = quota / jobCount + 1.0; -// qDebug() << Q_FUNC_INFO << "YYYY" << relativeLimitProgressDifference << downloadLimitPercent << jobCount; Q_FOREACH(GETFileJob *gfj, _downloadJobList) { gfj->setBandwidthLimited(true); gfj->setChoked(false); gfj->giveBandwidthQuota(quotaPerJob); -// qDebug() << Q_FUNC_INFO << "Gave" << quotaPerJob/1024.0 << "kB to" << gfj; + qCDebug(lcBandwidthManager) << "Gave" << quotaPerJob/1024.0 << "kB to" << gfj; } _relativeLimitCurrentMeasuredDevice = 0; } @@ -325,11 +320,11 @@ void BandwidthManager::relativeDownloadDelayTimerExpired() } if (_downloadJobList.isEmpty()) { - //qDebug() << Q_FUNC_INFO << _downloadJobList.count() << "No jobs?"; + qCDebug(lcBandwidthManager) << _downloadJobList.count() << "No jobs?"; return; } -// qDebug() << Q_FUNC_INFO << _downloadJobList.count() << "Starting measuring"; + qCDebug(lcBandwidthManager) << _downloadJobList.count() << "Starting measuring"; // Take first device and then append it again (= we round robin all devices) _relativeLimitCurrentMeasuredJob = _downloadJobList.takeFirst(); @@ -355,7 +350,7 @@ void BandwidthManager::relativeDownloadDelayTimerExpired() void BandwidthManager::switchingTimerExpired() { qint64 newUploadLimit = _propagator->_uploadLimit.fetchAndAddAcquire(0); if (newUploadLimit != _currentUploadLimit) { - qDebug() << Q_FUNC_INFO << "Upload Bandwidth limit changed" << _currentUploadLimit << newUploadLimit; + qCDebug(lcBandwidthManager) << "Upload Bandwidth limit changed" << _currentUploadLimit << newUploadLimit; _currentUploadLimit = newUploadLimit; Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) { if (newUploadLimit == 0) { @@ -372,7 +367,7 @@ void BandwidthManager::switchingTimerExpired() { } qint64 newDownloadLimit = _propagator->_downloadLimit.fetchAndAddAcquire(0); if (newDownloadLimit != _currentDownloadLimit) { - qDebug() << Q_FUNC_INFO << "Download Bandwidth limit changed" << _currentDownloadLimit << newDownloadLimit; + qCDebug(lcBandwidthManager) << "Download Bandwidth limit changed" << _currentDownloadLimit << newDownloadLimit; _currentDownloadLimit = newDownloadLimit; Q_FOREACH(GETFileJob *j, _downloadJobList) { if (usingAbsoluteDownloadLimit()) { @@ -393,18 +388,18 @@ void BandwidthManager::absoluteLimitTimerExpired() { if (usingAbsoluteUploadLimit() && _absoluteUploadDeviceList.count() > 0) { qint64 quotaPerDevice = _currentUploadLimit / qMax(1, _absoluteUploadDeviceList.count()); -// qDebug() << Q_FUNC_INFO << quotaPerDevice << _absoluteUploadDeviceList.count() << _currentUploadLimit; + qCDebug(lcBandwidthManager) << quotaPerDevice << _absoluteUploadDeviceList.count() << _currentUploadLimit; Q_FOREACH(UploadDevice *device, _absoluteUploadDeviceList) { device->giveBandwidthQuota(quotaPerDevice); -// qDebug() << Q_FUNC_INFO << "Gave " << quotaPerDevice/1024.0 << " kB to" << device; + qCDebug(lcBandwidthManager) << "Gave " << quotaPerDevice/1024.0 << " kB to" << device; } } if (usingAbsoluteDownloadLimit() && _downloadJobList.count() > 0) { qint64 quotaPerJob = _currentDownloadLimit / qMax(1, _downloadJobList.count()); -// qDebug() << Q_FUNC_INFO << quotaPerJob << _downloadJobList.count() << _currentDownloadLimit; + qCDebug(lcBandwidthManager) << quotaPerJob << _downloadJobList.count() << _currentDownloadLimit; Q_FOREACH(GETFileJob *j, _downloadJobList) { j->giveBandwidthQuota(quotaPerJob); -// qDebug() << Q_FUNC_INFO << "Gave " << quotaPerJob/1024.0 << " kB to" << j; + qCDebug(lcBandwidthManager) << "Gave " << quotaPerJob/1024.0 << " kB to" << j; } } } diff --git a/src/libsync/capabilities.cpp b/src/libsync/capabilities.cpp index 3721ad406..95459051f 100644 --- a/src/libsync/capabilities.cpp +++ b/src/libsync/capabilities.cpp @@ -17,7 +17,6 @@ #include "configfile.h" #include -#include namespace OCC { diff --git a/src/libsync/checksums.cpp b/src/libsync/checksums.cpp index b8b6ae067..c207a5b64 100644 --- a/src/libsync/checksums.cpp +++ b/src/libsync/checksums.cpp @@ -18,6 +18,7 @@ #include "propagatorjobs.h" #include "account.h" +#include #include /** \file checksums.cpp @@ -76,6 +77,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcChecksums, "sync.checksums", QtInfoMsg) + QByteArray makeChecksumHeader(const QByteArray& checksumType, const QByteArray& checksum) { QByteArray header = checksumType; @@ -155,7 +158,7 @@ QByteArray ComputeChecksum::computeNow(const QString& filePath, const QByteArray #endif // for an unknown checksum or no checksum, we're done right now if( !checksumType.isEmpty() ) { - qDebug() << "Unknown checksum type:" << checksumType; + qCDebug(lcChecksums) << "Unknown checksum type:" << checksumType; } return QByteArray(); } @@ -185,7 +188,7 @@ void ValidateChecksumHeader::start(const QString& filePath, const QByteArray& ch } if( !parseChecksumHeader(checksumHeader, &_expectedChecksumType, &_expectedChecksum) ) { - qDebug() << "Checksum header malformed:" << checksumHeader; + qCDebug(lcChecksums) << "Checksum header malformed:" << checksumHeader; emit validationFailed(tr("The checksum header is malformed.")); return; } @@ -235,13 +238,13 @@ QByteArray CSyncChecksumHook::compute(const QString& path, int checksumTypeId) { QByteArray checksumType = _journal->getChecksumType(checksumTypeId); if (checksumType.isEmpty()) { - qDebug() << "Checksum type" << checksumTypeId << "not found"; + qCDebug(lcChecksums) << "Checksum type" << checksumTypeId << "not found"; return QByteArray(); } QByteArray checksum = ComputeChecksum::computeNow(path, checksumType); if (checksum.isNull()) { - qDebug() << "Failed to compute checksum" << checksumType << "for" << path; + qCDebug(lcChecksums) << "Failed to compute checksum" << checksumType << "for" << path; return QByteArray(); } diff --git a/src/libsync/clientproxy.cpp b/src/libsync/clientproxy.cpp index 5cb9cde95..cebd5b826 100644 --- a/src/libsync/clientproxy.cpp +++ b/src/libsync/clientproxy.cpp @@ -15,11 +15,14 @@ #include "clientproxy.h" #include "configfile.h" +#include #include #include namespace OCC { +Q_LOGGING_CATEGORY(lcClientProxy, "sync.clientproxy", QtInfoMsg) + ClientProxy::ClientProxy(QObject *parent) : QObject(parent) { @@ -71,23 +74,23 @@ void ClientProxy::setupQtProxyFromConfig() switch(proxyType) { case QNetworkProxy::NoProxy: - qDebug() << "Set proxy configuration to use NO proxy"; + qCDebug(lcClientProxy) << "Set proxy configuration to use NO proxy"; QNetworkProxyFactory::setUseSystemConfiguration(false); QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy); break; case QNetworkProxy::DefaultProxy: - qDebug() << "Set proxy configuration to use system configuration"; + qCDebug(lcClientProxy) << "Set proxy configuration to use system configuration"; QNetworkProxyFactory::setUseSystemConfiguration(true); break; case QNetworkProxy::Socks5Proxy: proxy.setType(QNetworkProxy::Socks5Proxy); - qDebug() << "Set proxy configuration to SOCKS5" << printQNetworkProxy(proxy); + qCDebug(lcClientProxy) << "Set proxy configuration to SOCKS5" << printQNetworkProxy(proxy); QNetworkProxyFactory::setUseSystemConfiguration(false); QNetworkProxy::setApplicationProxy(proxy); break; case QNetworkProxy::HttpProxy: proxy.setType(QNetworkProxy::HttpProxy); - qDebug() << "Set proxy configuration to HTTP" << printQNetworkProxy(proxy); + qCDebug(lcClientProxy) << "Set proxy configuration to HTTP" << printQNetworkProxy(proxy); QNetworkProxyFactory::setUseSystemConfiguration(false); QNetworkProxy::setApplicationProxy(proxy); break; diff --git a/src/libsync/configfile.cpp b/src/libsync/configfile.cpp index bad5fd05d..458fc9f71 100644 --- a/src/libsync/configfile.cpp +++ b/src/libsync/configfile.cpp @@ -31,8 +31,8 @@ #include #include #include +#include #include -#include #include #define DEFAULT_REMOTE_POLL_INTERVAL 30000 // default remote poll time in milliseconds @@ -40,6 +40,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcConfigFile, "sync.configfile", QtInfoMsg) + //static const char caCertsKeyC[] = "CaCertificates"; only used from account.cpp static const char remotePollIntervalC[] = "remotePollInterval"; static const char forceSyncIntervalC[] = "forceSyncInterval"; @@ -92,8 +94,6 @@ ConfigFile::ConfigFile() QSettings settings(config, QSettings::IniFormat); settings.beginGroup( defaultConnection() ); - - // qDebug() << Q_FUNC_INFO << "Loading config: " << config << " (URL is " << settings.value("url").toString() << ")"; } bool ConfigFile::setConfDir(const QString &value) @@ -108,7 +108,7 @@ bool ConfigFile::setConfDir(const QString &value) } if( fi.exists() && fi.isDir() ) { dirPath = fi.absoluteFilePath(); - qDebug() << "** Using custom config dir " << dirPath; + qCDebug(lcConfigFile) << "** Using custom config dir " << dirPath; _confDir=dirPath; return true; } @@ -360,7 +360,7 @@ int ConfigFile::remotePollInterval( const QString& connection ) const int remoteInterval = settings.value( QLatin1String(remotePollIntervalC), DEFAULT_REMOTE_POLL_INTERVAL ).toInt(); if( remoteInterval < 5000) { - qDebug() << "Remote Interval is less than 5 seconds, reverting to" << DEFAULT_REMOTE_POLL_INTERVAL; + qCDebug(lcConfigFile) << "Remote Interval is less than 5 seconds, reverting to" << DEFAULT_REMOTE_POLL_INTERVAL; remoteInterval = DEFAULT_REMOTE_POLL_INTERVAL; } return remoteInterval; @@ -372,7 +372,7 @@ void ConfigFile::setRemotePollInterval(int interval, const QString &connection ) if( connection.isEmpty() ) con = defaultConnection(); if( interval < 5000 ) { - qDebug() << "Remote Poll interval of " << interval << " is below five seconds."; + qCDebug(lcConfigFile) << "Remote Poll interval of " << interval << " is below five seconds."; return; } QSettings settings(configFile(), QSettings::IniFormat); @@ -393,7 +393,7 @@ quint64 ConfigFile::forceSyncInterval(const QString& connection) const quint64 defaultInterval = 2 * 60 * 60 * 1000ull; // 2h quint64 interval = settings.value( QLatin1String(forceSyncIntervalC), defaultInterval ).toULongLong(); if( interval < pollInterval) { - qDebug() << "Force sync interval is less than the remote poll inteval, reverting to" << pollInterval; + qCDebug(lcConfigFile) << "Force sync interval is less than the remote poll inteval, reverting to" << pollInterval; interval = pollInterval; } return interval; @@ -409,7 +409,7 @@ quint64 ConfigFile::notificationRefreshInterval(const QString& connection) const quint64 defaultInterval = 5 * 60 * 1000ull; // 5 minutes quint64 interval = settings.value( QLatin1String(notificationRefreshIntervalC), defaultInterval ).toULongLong(); if( interval < 60*1000ull) { - qDebug() << "notification refresh interval smaller than one minute, setting to one minute"; + qCDebug(lcConfigFile) << "notification refresh interval smaller than one minute, setting to one minute"; interval = 60*1000ull; } return interval; @@ -427,7 +427,7 @@ int ConfigFile::updateCheckInterval( const QString& connection ) const int minInterval = 1000*60*5; if( interval < minInterval) { - qDebug() << "Update check interval less than five minutes, setting " << minInterval; + qCDebug(lcConfigFile) << "Update check interval less than five minutes, setting " << minInterval; interval = minInterval; } return interval; diff --git a/src/libsync/connectionvalidator.cpp b/src/libsync/connectionvalidator.cpp index e102243c2..c5bce6734 100644 --- a/src/libsync/connectionvalidator.cpp +++ b/src/libsync/connectionvalidator.cpp @@ -12,7 +12,9 @@ * for more details. */ -#include +#include +#include +#include #include #include #include @@ -25,6 +27,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcConnectionValidator, "sync.connectionvalidator", QtInfoMsg) + // Make sure the timeout for this job is less than how often we get called // This makes sure we get tried often enough without "ConnectionValidator already running" static qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5*1000); @@ -70,13 +74,13 @@ void ConnectionValidator::checkServerAndAuth() reportResult( NotConfigured ); return; } - qDebug() << "Checking server and authentication"; + qCDebug(lcConnectionValidator) << "Checking server and authentication"; _isCheckingServerAndAuth = true; // Lookup system proxy in a thread https://github.com/owncloud/client/issues/2993 if (ClientProxy::isUsingSystemDefault()) { - qDebug() << "Trying to look up system proxy"; + qCDebug(lcConnectionValidator) << "Trying to look up system proxy"; ClientProxy::lookupSystemProxyAsync(_account->url(), this, SLOT(systemProxyLookupDone(QNetworkProxy))); } else { @@ -89,14 +93,14 @@ void ConnectionValidator::checkServerAndAuth() void ConnectionValidator::systemProxyLookupDone(const QNetworkProxy &proxy) { if (!_account) { - qDebug() << "Bailing out, Account had been deleted"; + qCDebug(lcConnectionValidator) << "Bailing out, Account had been deleted"; return; } if (proxy.type() != QNetworkProxy::NoProxy) { - qDebug() << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy); + qCDebug(lcConnectionValidator) << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy); } else { - qDebug() << "No system proxy set by OS"; + qCDebug(lcConnectionValidator) << "No system proxy set by OS"; } _account->networkAccessManager()->setProxy(proxy); @@ -123,7 +127,7 @@ void ConnectionValidator::slotStatusFound(const QUrl&url, const QJsonObject &inf QString serverVersion = CheckServerJob::version(info); // status.php was found. - qDebug() << "** Application: ownCloud found: " + qCDebug(lcConnectionValidator) << "** Application: ownCloud found: " << url << " with version " << CheckServerJob::versionString(info) << "(" << serverVersion << ")"; @@ -148,7 +152,7 @@ void ConnectionValidator::slotStatusFound(const QUrl&url, const QJsonObject &inf void ConnectionValidator::slotNoStatusFound(QNetworkReply *reply) { auto job = qobject_cast(sender()); - qDebug() << Q_FUNC_INFO << reply->error() << job->errorString() << reply->peek(1024); + qCDebug(lcConnectionValidator) << reply->error() << job->errorString() << reply->peek(1024); if (!_account->credentials()->ready()) { // This could be needed for SSL client certificates // We need to load them from keychain and try @@ -181,7 +185,7 @@ void ConnectionValidator::checkAuthentication() // simply GET the webdav root, will fail if credentials are wrong. // continue in slotAuthCheck here :-) - qDebug() << "# Check whether authenticated propfind works."; + qCDebug(lcConnectionValidator) << "# Check whether authenticated propfind works."; PropfindJob *job = new PropfindJob(_account, "/", this); job->setTimeout(timeoutToUseMsec); job->setProperties(QList() << "getlastmodified"); @@ -197,8 +201,8 @@ void ConnectionValidator::slotAuthFailed(QNetworkReply *reply) if( reply->error() == QNetworkReply::AuthenticationRequiredError || !_account->credentials()->stillValid(reply)) { - qDebug() << reply->error() << job->errorString(); - qDebug() << "******** Password is wrong!"; + qCDebug(lcConnectionValidator) << reply->error() << job->errorString(); + qCDebug(lcConnectionValidator) << "******** Password is wrong!"; _errors << tr("The provided credentials are not correct"); stat = CredentialsMissingOrWrong; @@ -237,7 +241,7 @@ void ConnectionValidator::checkServerCapabilities() void ConnectionValidator::slotCapabilitiesRecieved(const QJsonDocument &json) { auto caps = json.object().value("ocs").toObject().value("data").toObject().value("capabilities").toObject(); - qDebug() << "Server capabilities" << caps; + qCDebug(lcConnectionValidator) << "Server capabilities" << caps; _account->setCapabilities(caps.toVariantMap()); // New servers also report the version in the capabilities @@ -260,7 +264,7 @@ void ConnectionValidator::fetchUser() bool ConnectionValidator::setAndCheckServerVersion(const QString& version) { - qDebug() << _account->url() << "has server version" << version; + qCInfo(lcConnectionValidator) << _account->url() << "has server version" << version; _account->setServerVersion(version); // We cannot deal with servers < 5.0.0 diff --git a/src/libsync/cookiejar.cpp b/src/libsync/cookiejar.cpp index b3e205628..836b5d1ba 100644 --- a/src/libsync/cookiejar.cpp +++ b/src/libsync/cookiejar.cpp @@ -16,14 +16,16 @@ #include "configfile.h" -#include #include #include +#include #include #include namespace OCC { +Q_LOGGING_CATEGORY(lcCookieJar, "sync.cookiejar", QtInfoMsg) + namespace { const unsigned int JAR_VERSION = 23; } @@ -55,7 +57,7 @@ QDataStream &operator>>(QDataStream &stream, QList &list) stream >> value; QList newCookies = QNetworkCookie::parseCookies(value); if (newCookies.count() == 0 && value.length() != 0) { - qWarning() << "CookieJar: Unable to parse saved cookie:" << value; + qCWarning(lcCookieJar) << "CookieJar: Unable to parse saved cookie:" << value; } for (int j = 0; j < newCookies.count(); ++j) list.append(newCookies.at(j)); @@ -87,7 +89,7 @@ bool CookieJar::setCookiesFromUrl(const QList& cookieList, const QList CookieJar::cookiesForUrl(const QUrl &url) const { QList cookies = QNetworkCookieJar::cookiesForUrl(url); -// qDebug() << url << "requests:" << cookies; + qCDebug(lcCookieJar) << url << "requests:" << cookies; return cookies; } @@ -100,7 +102,7 @@ void CookieJar::save(const QString &fileName) { QFile file; file.setFileName(fileName); - qDebug() << fileName; + qCDebug(lcCookieJar) << fileName; file.open(QIODevice::WriteOnly); QDataStream stream(&file); stream << removeExpired(allCookies()); diff --git a/src/libsync/creds/abstractcredentials.cpp b/src/libsync/creds/abstractcredentials.cpp index f3f38b22a..233ca9cea 100644 --- a/src/libsync/creds/abstractcredentials.cpp +++ b/src/libsync/creds/abstractcredentials.cpp @@ -12,8 +12,8 @@ * for more details. */ +#include #include -#include #include "asserts.h" #include "creds/abstractcredentials.h" @@ -21,6 +21,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcCredentials, "sync.credentials", QtInfoMsg) + AbstractCredentials::AbstractCredentials() : _account(0) { @@ -36,11 +38,11 @@ QString AbstractCredentials::keychainKey(const QString &url, const QString &user { QString u(url); if( u.isEmpty() ) { - qDebug() << "Empty url in keyChain, error!"; + qCDebug(lcCredentials) << "Empty url in keyChain, error!"; return QString::null; } if( user.isEmpty() ) { - qDebug() << "Error: User is empty!"; + qCDebug(lcCredentials) << "Error: User is empty!"; return QString::null; } diff --git a/src/libsync/creds/credentialscommon.cpp b/src/libsync/creds/credentialscommon.cpp index c13019f63..34181a8b0 100644 --- a/src/libsync/creds/credentialscommon.cpp +++ b/src/libsync/creds/credentialscommon.cpp @@ -19,8 +19,6 @@ #include #include -#include - #include "creds/credentialscommon.h" #include "utility.h" diff --git a/src/libsync/creds/httpcredentials.cpp b/src/libsync/creds/httpcredentials.cpp index 980cb4e54..56d67c29a 100644 --- a/src/libsync/creds/httpcredentials.cpp +++ b/src/libsync/creds/httpcredentials.cpp @@ -13,8 +13,8 @@ * for more details. */ +#include #include -#include #include #include #include @@ -34,6 +34,8 @@ using namespace QKeychain; namespace OCC { +Q_LOGGING_CATEGORY(lcHttpCredentials, "sync.credentials.http", QtInfoMsg) + namespace { const char userC[] = "user"; @@ -51,10 +53,6 @@ protected: QByteArray credHash = QByteArray(_cred->user().toUtf8()+":"+_cred->password().toUtf8()).toBase64(); QNetworkRequest req(request); req.setRawHeader(QByteArray("Authorization"), QByteArray("Basic ") + credHash); - //qDebug() << "Request for " << req.url() << "with authorization" - // << QByteArray::fromBase64(credHash) - // << _cred->_clientSslKey << _cred->_clientSslCertificate - // << _cred->_clientSslKey.isNull() << _cred->_clientSslCertificate.isNull(); if (!_cred->_clientSslKey.isNull() && !_cred->_clientSslCertificate.isNull()) { // SSL configuration @@ -155,7 +153,7 @@ void HttpCredentials::fetchFromKeychain() addSettingsToJob(_account, job); job->setInsecureFallback(false); job->setKey(kck); - qDebug() << "-------- ----->" << _clientSslCertificate << _clientSslKey; + qCDebug(lcHttpCredentials) << "-------- ----->" << _clientSslCertificate << _clientSslKey; connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadClientCertPEMJobDone(QKeychain::Job*))); job->start(); @@ -204,7 +202,7 @@ void HttpCredentials::slotReadClientKeyPEMJobDone(QKeychain::Job* incoming) } #endif if (_clientSslKey.isNull()) { - qDebug() << "Warning: Could not load SSL key into Qt!"; + qCDebug(lcHttpCredentials) << "Warning: Could not load SSL key into Qt!"; } } @@ -234,7 +232,7 @@ void HttpCredentials::slotReadJobDone(QKeychain::Job *incomingJob) _password = job->textData(); if( _user.isEmpty()) { - qDebug() << "Strange: User is empty!"; + qCDebug(lcHttpCredentials) << "Strange: User is empty!"; } QKeychain::Error error = job->error(); @@ -270,7 +268,7 @@ void HttpCredentials::invalidateToken() const QString kck = keychainKey(_account->url().toString(), _user); if( kck.isEmpty() ) { - qDebug() << "InvalidateToken: User is empty, bailing out!"; + qCDebug(lcHttpCredentials) << "InvalidateToken: User is empty, bailing out!"; return; } @@ -365,7 +363,7 @@ void HttpCredentials::slotWriteJobDone(QKeychain::Job *job) case NoError: break; default: - qDebug() << "Error while writing password" << job->errorString(); + qCDebug(lcHttpCredentials) << "Error while writing password" << job->errorString(); } WritePasswordJob *wjob = qobject_cast(job); wjob->deleteLater(); @@ -376,7 +374,7 @@ void HttpCredentials::slotAuthentication(QNetworkReply* reply, QAuthenticator* a Q_UNUSED(authenticator) // Because of issue #4326, we need to set the login and password manually at every requests // Thus, if we reach this signal, those credentials were invalid and we terminate. - qDebug() << "Stop request: Authentication failed for " << reply->url().toString(); + qCDebug(lcHttpCredentials) << "Stop request: Authentication failed for " << reply->url().toString(); reply->setProperty(authenticationFailedC, true); reply->close(); } diff --git a/src/libsync/creds/tokencredentials.cpp b/src/libsync/creds/tokencredentials.cpp index 7ea4cf865..221d830dd 100644 --- a/src/libsync/creds/tokencredentials.cpp +++ b/src/libsync/creds/tokencredentials.cpp @@ -13,8 +13,8 @@ * for more details. */ +#include #include -#include #include #include #include @@ -30,6 +30,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcTokenCredentials, "sync.credentials.token", QtInfoMsg) + namespace { @@ -45,7 +47,7 @@ public: protected: QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) { if (_cred->user().isEmpty() || _cred->password().isEmpty()) { - qWarning() << Q_FUNC_INFO << "Empty user/password provided!"; + qCWarning(lcTokenCredentials) << "Empty user/password provided!"; } QNetworkRequest req(request); @@ -131,7 +133,7 @@ bool TokenCredentials::stillValid(QNetworkReply *reply) void TokenCredentials::invalidateToken() { - qDebug() << Q_FUNC_INFO; + qCDebug(lcTokenCredentials) << "Invalidating token"; _ready = false; _account->clearCookieJar(); _token = QString(); @@ -155,7 +157,7 @@ void TokenCredentials::slotAuthentication(QNetworkReply* reply, QAuthenticator* // we cannot use QAuthenticator, because it sends username and passwords with latin1 // instead of utf8 encoding. Instead, we send it manually. Thus, if we reach this signal, // those credentials were invalid and we terminate. - qDebug() << "Stop request: Authentication failed for " << reply->url().toString(); + qCDebug(lcTokenCredentials) << "Stop request: Authentication failed for " << reply->url().toString(); reply->setProperty(authenticationFailedC, true); reply->close(); } diff --git a/src/libsync/discoveryphase.cpp b/src/libsync/discoveryphase.cpp index 6ef801243..c9c78e73f 100644 --- a/src/libsync/discoveryphase.cpp +++ b/src/libsync/discoveryphase.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include #include @@ -29,6 +29,7 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcDiscovery, "sync.discovery", QtInfoMsg) /* Given a sorted list of paths ending with '/', return whether or not the given path is within one of the paths of the list*/ static bool findPathInList(const QStringList &list, const QString &path) @@ -286,7 +287,7 @@ static csync_vio_file_stat_t* propertyMapToFileStat(const QMap csync_vio_file_stat_t* file_stat = csync_vio_file_stat_new(); for (auto it = map.constBegin(); it != map.constEnd(); ++it) { - //qDebug() << it.key() << it.value(); + qCDebug(lcDiscovery) << "Property key:" << it.key() << "with value:" << it.value(); QString property = it.key(); QString value = it.value(); if (property == "resourcetype") { @@ -329,7 +330,7 @@ static csync_vio_file_stat_t* propertyMapToFileStat(const QMap strcpy(file_stat->remotePerm, v.constData()); file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_PERM; } else { - qWarning() << "permissions too large" << v; + qCWarning(lcDiscovery) << "permissions too large" << v; } } } @@ -339,7 +340,6 @@ static csync_vio_file_stat_t* propertyMapToFileStat(const QMap void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap &map) { - //qDebug() << Q_FUNC_INFO << _subPath << file << map.count() << map.keys() << _account->davPath() << _lsColJob->reply()->request().url().path(); if (!_ignoredFirst) { // The first entry is for the folder itself, we should process it differently. _ignoredFirst = true; @@ -367,7 +367,7 @@ void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, con FileStatPointer file_stat(propertyMapToFileStat(map)); file_stat->name = strdup(file.toUtf8()); if (!file_stat->etag || strlen(file_stat->etag) == 0) { - qDebug() << "WARNING: etag of" << file_stat->name << "is" << file_stat->etag << " This must not happen."; + qCDebug(lcDiscovery) << "WARNING: etag of" << file_stat->name << "is" << file_stat->etag << " This must not happen."; } if (_isExternalStorage) { /* All the entries in a external storage have 'M' in their permission. However, for all @@ -382,7 +382,6 @@ void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, con if( slashPos > -1 ) { fileRef = file.midRef(slashPos+1); } - //qDebug() << "!!!!" << file_stat << file_stat->name << file_stat->file_id << map.count(); _results.append(file_stat); } @@ -418,7 +417,7 @@ void DiscoverySingleDirectoryJob::lsJobFinishedWithErrorSlot(QNetworkReply *r) QString httpReason = r->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); QString msg = r->errorString(); int errnoCode = EIO; // Something went wrong - qDebug() << Q_FUNC_INFO << r->errorString() << httpCode << r->error(); + qCDebug(lcDiscovery) << r->errorString() << httpCode << r->error(); if (httpCode != 0 && httpCode != 207) { errnoCode = get_errno_from_http_errcode(httpCode, httpReason); } else if (r->error() != QNetworkReply::NoError) { @@ -493,7 +492,7 @@ void DiscoveryMainThread::singleDirectoryJobResultSlot(const QListpath; + qCDebug(lcDiscovery) << "Have" << result.count() << "results for " << _currentDiscoveryDirectoryResult->path; _currentDiscoveryDirectoryResult->list = result; @@ -516,7 +515,7 @@ void DiscoveryMainThread::singleDirectoryJobFinishedWithErrorSlot(int csyncErrno if (!_currentDiscoveryDirectoryResult) { return; // possibly aborted } - qDebug() << Q_FUNC_INFO << csyncErrnoCode << msg; + qCDebug(lcDiscovery) << csyncErrnoCode << msg; _currentDiscoveryDirectoryResult->code = csyncErrnoCode; _currentDiscoveryDirectoryResult->msg = msg; @@ -531,7 +530,7 @@ void DiscoveryMainThread::singleDirectoryJobFirstDirectoryPermissionsSlot(const { // Should be thread safe since the sync thread is blocked if (!_discoveryJob->_csync_ctx->remote.root_perms) { - qDebug() << "Permissions for root dir:" << p; + qCDebug(lcDiscovery) << "Permissions for root dir:" << p; _discoveryJob->_csync_ctx->remote.root_perms = strdup(p.toUtf8()); } } @@ -566,7 +565,7 @@ void DiscoveryMainThread::slotGetSizeFinishedWithError() return; // possibly aborted } - qWarning() << "Error getting the size of the directory"; + qCWarning(lcDiscovery) << "Error getting the size of the directory"; // just let let the discovery job continue then _currentGetSizeResult = 0; QMutexLocker locker(&_discoveryJob->_vioMutex); @@ -581,7 +580,7 @@ void DiscoveryMainThread::slotGetSizeResult(const QVariantMap &map) } *_currentGetSizeResult = map.value(QLatin1String("size")).toLongLong(); - qDebug() << "Size of folder:" << *_currentGetSizeResult; + qCDebug(lcDiscovery) << "Size of folder:" << *_currentGetSizeResult; _currentGetSizeResult = 0; QMutexLocker locker(&_discoveryJob->_vioMutex); _discoveryJob->_vioWaitCondition.wakeAll(); @@ -619,7 +618,7 @@ csync_vio_handle_t* DiscoveryJob::remote_vio_opendir_hook (const char *url, { DiscoveryJob *discoveryJob = static_cast(userdata); if (discoveryJob) { - qDebug() << discoveryJob << url << "Calling into main thread..."; + qCDebug(lcDiscovery) << discoveryJob << url << "Calling into main thread..."; QScopedPointer directoryResult(new DiscoveryDirectoryResult()); directoryResult->code = EIO; @@ -630,11 +629,11 @@ csync_vio_handle_t* DiscoveryJob::remote_vio_opendir_hook (const char *url, discoveryJob->_vioWaitCondition.wait(&discoveryJob->_vioMutex, ULONG_MAX); // FIXME timeout? discoveryJob->_vioMutex.unlock(); - qDebug() << discoveryJob << url << "...Returned from main thread"; + qCDebug(lcDiscovery) << discoveryJob << url << "...Returned from main thread"; // Upon awakening from the _vioWaitCondition, iterator should be a valid iterator. if (directoryResult->code != 0) { - qDebug() << directoryResult->code << "when opening" << url << "msg=" << directoryResult->msg; + qCDebug(lcDiscovery) << directoryResult->code << "when opening" << url << "msg=" << directoryResult->msg; errno = directoryResult->code; // save the error string to the context discoveryJob->_csync_ctx->error_string = qstrdup( directoryResult->msg.toUtf8().constData() ); @@ -668,7 +667,7 @@ void DiscoveryJob::remote_vio_closedir_hook (csync_vio_handle_t *dhandle, void if (discoveryJob) { DiscoveryDirectoryResult *directoryResult = static_cast (dhandle); QString path = directoryResult->path; - qDebug() << Q_FUNC_INFO << discoveryJob << path; + qCDebug(lcDiscovery) << discoveryJob << path; delete directoryResult; // just deletes the struct and the iterator, the data itself is owned by the SyncEngine/DiscoveryMainThread } } diff --git a/src/libsync/filesystem.cpp b/src/libsync/filesystem.cpp index 044ea3904..d6ab41822 100644 --- a/src/libsync/filesystem.cpp +++ b/src/libsync/filesystem.cpp @@ -17,8 +17,8 @@ #include "utility.h" #include #include +#include #include -#include #include #ifdef ZLIB_FOUND @@ -50,6 +50,8 @@ extern "C" { namespace OCC { +Q_LOGGING_CATEGORY(lcFileSystem, "sync.filesystem", QtInfoMsg) + QString FileSystem::longWinPath( const QString& inpath ) { QString path(inpath); @@ -66,7 +68,7 @@ bool FileSystem::fileEquals(const QString& fn1, const QString& fn2) QFile f1(fn1); QFile f2(fn2); if (!f1.open(QIODevice::ReadOnly) || !f2.open(QIODevice::ReadOnly)) { - qDebug() << "fileEquals: Failed to open " << fn1 << "or" << fn2; + qCDebug(lcFileSystem) << "fileEquals: Failed to open " << fn1 << "or" << fn2; return false; } @@ -178,7 +180,7 @@ time_t FileSystem::getModTime(const QString &filename) && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_MTIME)) { result = stat->mtime; } else { - qDebug() << "Could not get modification time for" << filename + qCDebug(lcFileSystem) << "Could not get modification time for" << filename << "with csync, using QFileInfo"; result = Utility::qDateTimeToTime_t(QFileInfo(filename).lastModified()); } @@ -193,7 +195,7 @@ bool FileSystem::setModTime(const QString& filename, time_t modTime) times[0].tv_usec = times[1].tv_usec = 0; int rc = c_utimes(filename.toUtf8().data(), times); if (rc != 0) { - qDebug() << "Error setting mtime for" << filename + qCDebug(lcFileSystem) << "Error setting mtime for" << filename << "failed: rc" << rc << ", errno:" << errno; return false; } @@ -241,7 +243,7 @@ bool FileSystem::rename(const QString &originFileName, } if (!success) { - qDebug() << "FAIL: renaming file" << originFileName + qCDebug(lcFileSystem) << "FAIL: renaming file" << originFileName << "to" << destinationFileName << "failed: " << error; if (errorString) { @@ -266,7 +268,7 @@ bool FileSystem::verifyFileUnchanged(const QString& fileName, const qint64 actualSize = getSize(fileName); const time_t actualMtime = getModTime(fileName); if (actualSize != previousSize || actualMtime != previousMtime) { - qDebug() << "File" << fileName << "has changed:" + qCDebug(lcFileSystem) << "File" << fileName << "has changed:" << "size: " << previousSize << "<->" << actualSize << ", mtime: " << previousMtime << "<->" << actualMtime; return false; @@ -301,7 +303,6 @@ bool FileSystem::uncheckedRenameReplace(const QString& originFileName, QFile orig(originFileName); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) success = orig.fileEngine()->rename(destinationFileName); - // qDebug() << "Renaming " << tmpFile.fileName() << " to " << fn; #else // We want a rename that also overwites. QFile::rename does not overwite. // Qt 5.1 has QSaveFile::renameOverwrite we could use. @@ -310,7 +311,7 @@ bool FileSystem::uncheckedRenameReplace(const QString& originFileName, bool destExists = fileExists(destinationFileName); if( destExists && !QFile::remove(destinationFileName) ) { *errorString = orig.errorString(); - qDebug() << Q_FUNC_INFO << "Target file could not be removed."; + qCDebug(lcFileSystem) << "Target file could not be removed."; success = false; } if( success ) { @@ -319,7 +320,7 @@ bool FileSystem::uncheckedRenameReplace(const QString& originFileName, #endif if (!success) { *errorString = orig.errorString(); - qDebug() << "FAIL: renaming temp file to final failed: " << *errorString ; + qCDebug(lcFileSystem) << "FAIL: renaming temp file to final failed: " << *errorString ; return false; } @@ -343,7 +344,7 @@ bool FileSystem::uncheckedRenameReplace(const QString& originFileName, (LPWSTR)&string, 0, NULL); *errorString = QString::fromWCharArray(string); - qDebug() << "FAIL: renaming temp file to final failed: " << *errorString; + qCDebug(lcFileSystem) << "FAIL: renaming temp file to final failed: " << *errorString; LocalFree((HLOCAL)string); return false; } @@ -433,7 +434,7 @@ static qint64 getSizeWithCsync(const QString& filename) && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_SIZE)) { result = stat->size; } else { - qDebug() << "Could not get size for" << filename << "with csync"; + qCDebug(lcFileSystem) << "Could not get size for" << filename << "with csync"; } csync_vio_file_stat_destroy(stat); return result; diff --git a/src/libsync/networkjobs.cpp b/src/libsync/networkjobs.cpp index 015bcf2d4..142fd0635 100644 --- a/src/libsync/networkjobs.cpp +++ b/src/libsync/networkjobs.cpp @@ -13,6 +13,7 @@ * for more details. */ +#include #include #include #include @@ -25,7 +26,6 @@ #include #include #include -#include #include #include #include @@ -39,6 +39,14 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcEtag, "sync.networkjob.etag", QtInfoMsg) +Q_LOGGING_CATEGORY(lcLsCol, "sync.networkjob.lscol", QtInfoMsg) +Q_LOGGING_CATEGORY(lcCheckServer, "sync.networkjob.checkserver", QtInfoMsg) +Q_LOGGING_CATEGORY(lcPropfind, "sync.networkjob.propfind", QtInfoMsg) +Q_LOGGING_CATEGORY(lcAvatar, "sync.networkjob.avatar", QtInfoMsg) +Q_LOGGING_CATEGORY(lcProppatch, "sync.networkjob.proppatch", QtInfoMsg) +Q_LOGGING_CATEGORY(lcJsonApi, "sync.networkjob.jsonapi", QtInfoMsg) + RequestEtagJob::RequestEtagJob(AccountPtr account, const QString &path, QObject *parent) : AbstractNetworkJob(account, path, parent) { @@ -71,7 +79,7 @@ void RequestEtagJob::start() sendRequest("PROPFIND", makeDavUrl(path()), req, buf); if( reply()->error() != QNetworkReply::NoError ) { - qDebug() << "getting etag: request network error: " << reply()->errorString(); + qCDebug(lcEtag) << "request network error: " << reply()->errorString(); } AbstractNetworkJob::start(); } @@ -190,7 +198,7 @@ bool LsColXMLParser::parse( const QByteArray& xml, QHash *sizes // but the result will have URL encoding.. QString hrefString = QString::fromUtf8(QByteArray::fromPercentEncoding(reader.readElementText().toUtf8())); if (!hrefString.startsWith(expectedPath)) { - qDebug() << "Invalid href" << hrefString << "expected starting with" << expectedPath; + qCDebug(lcLsCol) << "Invalid href" << hrefString << "expected starting with" << expectedPath; return false; } currentHref = hrefString; @@ -254,10 +262,10 @@ bool LsColXMLParser::parse( const QByteArray& xml, QHash *sizes if (reader.hasError()) { // XML Parser error? Whatever had been emitted before will come as directoryListingIterated - qDebug() << "ERROR" << reader.errorString() << xml; + qCDebug(lcLsCol) << "ERROR" << reader.errorString() << xml; return false; } else if (!insideMultiStatus) { - qDebug() << "ERROR no WebDAV response?" << xml; + qCDebug(lcLsCol) << "ERROR no WebDAV response?" << xml; return false; } else { emit directoryListingSubfolders(folders); @@ -294,7 +302,7 @@ void LsColJob::start() QList properties = _properties; if (properties.isEmpty()) { - qWarning() << "Propfind with no properties!"; + qCWarning(lcLsCol) << "Propfind with no properties!"; } QByteArray propStr; foreach (const QByteArray &prop, properties) { @@ -388,11 +396,11 @@ void CheckServerJob::start() void CheckServerJob::onTimedOut() { - qDebug() << "TIMEOUT" << Q_FUNC_INFO; + qCDebug(lcCheckServer) << "TIMEOUT"; if (reply() && reply()->isRunning()) { emit timeout(reply()->url()); } else if (!reply()) { - qDebug() << Q_FUNC_INFO << "Timeout even there was no reply?"; + qCDebug(lcCheckServer) << "Timeout even there was no reply?"; } deleteLater(); } @@ -445,7 +453,7 @@ bool CheckServerJob::finished() if (reply()->request().url().scheme() == QLatin1String("https") && reply()->sslConfiguration().sessionTicket().isEmpty() && reply()->error() == QNetworkReply::NoError) { - qDebug() << "No SSL session identifier / session ticket is used, this might impact sync performance negatively."; + qCDebug(lcCheckServer) << "No SSL session identifier / session ticket is used, this might impact sync performance negatively."; } #endif @@ -457,28 +465,28 @@ bool CheckServerJob::finished() _subdirFallback = true; setPath(QLatin1String(owncloudDirC)+QLatin1String(statusphpC)); start(); - qDebug() << "Retrying with" << reply()->url(); + qCDebug(lcCheckServer) << "Retrying with" << reply()->url(); return false; } QByteArray body = reply()->peek(4*1024); int httpStatus = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if( body.isEmpty() || httpStatus != 200) { - qDebug() << "error: status.php replied " << httpStatus << body; + qCDebug(lcCheckServer) << "error: status.php replied " << httpStatus << body; emit instanceNotFound(reply()); } else { QJsonParseError error; auto status = QJsonDocument::fromJson(body, &error); // empty or invalid response if (error.error != QJsonParseError::NoError || status.isNull()) { - qDebug() << "status.php from server is not valid JSON!" << body << reply()->request().url() << error.errorString(); + qCDebug(lcCheckServer) << "status.php from server is not valid JSON!" << body << reply()->request().url() << error.errorString(); } - qDebug() << "status.php returns: " << status << " " << reply()->error() << " Reply: " << reply(); + qCDebug(lcCheckServer) << "status.php returns: " << status << " " << reply()->error() << " Reply: " << reply(); if( status.object().contains("installed") ) { emit instanceFound(reply()->url(), status.object()); } else { - qDebug() << "No proper answer on " << reply()->url(); + qCDebug(lcCheckServer) << "No proper answer on " << reply()->url(); emit instanceNotFound(reply()); } } @@ -498,7 +506,7 @@ void PropfindJob::start() QList properties = _properties; if (properties.isEmpty()) { - qWarning() << "Propfind with no properties!"; + qCWarning(lcLsCol) << "Propfind with no properties!"; } QNetworkRequest req; // Always have a higher priority than the propagator because we use this from the UI @@ -568,13 +576,13 @@ bool PropfindJob::finished() } } if (reader.hasError()) { - qDebug() << "PROPFIND request XML parser error: " << reader.errorString(); + qCDebug(lcPropfind) << "XML parser error: " << reader.errorString(); emit finishedWithError(reply()); } else { emit result(items); } } else { - qDebug() << "PROPFIND request *not* successful, http result code is" << http_result_code + qCDebug(lcPropfind) << "*not* successful, http result code is" << http_result_code << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String("")); emit finishedWithError(reply()); } @@ -608,7 +616,7 @@ bool AvatarJob::finished() if( pngData.size() ) { if( avImage.loadFromData(pngData) ) { - qDebug() << "Retrieved Avatar pixmap!"; + qCDebug(lcAvatar) << "Retrieved Avatar pixmap!"; } } } @@ -627,7 +635,7 @@ ProppatchJob::ProppatchJob(AccountPtr account, const QString &path, QObject *par void ProppatchJob::start() { if (_properties.isEmpty()) { - qWarning() << "Proppatch with no properties!"; + qCWarning(lcProppatch) << "Proppatch with no properties!"; } QNetworkRequest req; @@ -682,7 +690,7 @@ bool ProppatchJob::finished() if (http_result_code == 207) { emit success(); } else { - qDebug() << "PROPPATCH request *not* successful, http result code is" << http_result_code + qCDebug(lcProppatch) << "*not* successful, http result code is" << http_result_code << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String("")); emit finishedWithError(); } @@ -735,7 +743,7 @@ bool JsonApiJob::finished() int statusCode = 0; if (reply()->error() != QNetworkReply::NoError) { - qWarning() << "Network error: " << path() << errorString() << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute); + qCWarning(lcJsonApi) << "Network error: " << path() << errorString() << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute); emit jsonReceived(QJsonDocument(), statusCode); return true; } @@ -760,7 +768,7 @@ bool JsonApiJob::finished() auto json = QJsonDocument::fromJson(jsonStr.toUtf8(), &error); // empty or invalid response if (error.error != QJsonParseError::NoError || json.isNull()) { - qWarning() << "invalid JSON!" << jsonStr << error.errorString(); + qCWarning(lcJsonApi) << "invalid JSON!" << jsonStr << error.errorString(); emit jsonReceived(json, statusCode); return true; } diff --git a/src/libsync/owncloudpropagator.cpp b/src/libsync/owncloudpropagator.cpp index 14c8b5edc..6559ba2fc 100644 --- a/src/libsync/owncloudpropagator.cpp +++ b/src/libsync/owncloudpropagator.cpp @@ -35,14 +35,18 @@ #include #include #include +#include #include #include #include -#include #include namespace OCC { +Q_LOGGING_CATEGORY(lcPropagator, "sync.propagator", QtInfoMsg) +Q_LOGGING_CATEGORY(lcDirectory, "sync.propagator.directory", QtInfoMsg) +Q_LOGGING_CATEGORY(lcCleanupPolls, "sync.propagator.cleanuppolls", QtInfoMsg) + qint64 criticalFreeSpaceLimit() { qint64 value = 50 * 1000 * 1000LL; @@ -142,11 +146,11 @@ static SyncJournalErrorBlacklistRecord createBlacklistEntry( entry._ignoreDuration = old._ignoreDuration * 5; if( item._httpErrorCode == 403 ) { - qDebug() << "Probably firewall error: " << item._httpErrorCode << ", blacklisting up to 1h only"; + qCDebug(lcPropagator) << "Probably firewall error: " << item._httpErrorCode << ", blacklisting up to 1h only"; entry._ignoreDuration = qMin(entry._ignoreDuration, time_t(60*60)); } else if( item._httpErrorCode == 413 || item._httpErrorCode == 415 ) { - qDebug() << "Fatal Error condition" << item._httpErrorCode << ", maximum blacklist ignore time!"; + qCDebug(lcPropagator) << "Fatal Error condition" << item._httpErrorCode << ", maximum blacklist ignore time!"; entry._ignoreDuration = maxBlacklistTime; } @@ -193,7 +197,7 @@ static void blacklistUpdate(SyncJournalDb* journal, SyncFileItem& item) item._status = SyncFileItem::FileIgnored; item._errorString.prepend(PropagateItemJob::tr("Continue blacklisting:") + " "); - qDebug() << "blacklisting " << item._file + qCDebug(lcPropagator) << "blacklisting " << item._file << " for " << newEntry._ignoreDuration << ", retry count " << newEntry._retryCount; @@ -203,7 +207,7 @@ static void blacklistUpdate(SyncJournalDb* journal, SyncFileItem& item) // Some soft errors might become louder on repeat occurrence if (item._status == SyncFileItem::SoftError && newEntry._retryCount > 1) { - qDebug() << "escalating soft error on " << item._file + qCDebug(lcPropagator) << "escalating soft error on " << item._file << " to normal error, " << item._httpErrorCode; item._status = SyncFileItem::NormalError; return; @@ -440,7 +444,7 @@ void OwncloudPropagator::start(const SyncFileItemVector& items) } else if (item->_instruction == CSYNC_INSTRUCTION_RENAME) { // all is good, the rename will be executed before the directory deletion } else { - qWarning() << "WARNING: Job within a removed directory? This should not happen!" + qCWarning(lcPropagator) << "WARNING: Job within a removed directory? This should not happen!" << item->_file << item->_instruction; } } @@ -503,7 +507,7 @@ void OwncloudPropagator::start(const SyncFileItemVector& items) connect(_rootJob.data(), SIGNAL(finished(SyncFileItem::Status)), this, SLOT(emitFinished(SyncFileItem::Status))); - qDebug() << "Using QNAM/HTTP parallel code path"; + qCDebug(lcPropagator) << "Using QNAM/HTTP parallel code path"; scheduleNextJob(); } @@ -560,32 +564,29 @@ bool OwncloudPropagator::localFileNameClash( const QString& relFile ) QFileInfo fileInfo(file); if (!fileInfo.exists()) { re = false; - qDebug() << Q_FUNC_INFO << "No valid fileinfo"; + qCDebug(lcPropagator) << "No valid fileinfo"; } else { // Need to normalize to composited form because of // https://bugreports.qt-project.org/browse/QTBUG-39622 const QString cName = fileInfo.canonicalFilePath().normalized(QString::NormalizationForm_C); - // qDebug() << Q_FUNC_INFO << "comparing " << cName << " with " << file; bool equal = (file == cName); re = (!equal && ! cName.endsWith(relFile, Qt::CaseSensitive) ); - // qDebug() << Q_FUNC_INFO << "Returning for localFileNameClash: " << re; } #elif defined(Q_OS_WIN) const QString file( _localDir + relFile ); - qDebug() << "CaseClashCheck for " << file; + qCDebug(lcPropagator) << "CaseClashCheck for " << file; WIN32_FIND_DATA FindFileData; HANDLE hFind; hFind = FindFirstFileW( (wchar_t*)file.utf16(), &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { - //qDebug() << "FindFirstFile failed " << GetLastError(); // returns false. } else { QString realFileName = QString::fromWCharArray( FindFileData.cFileName ); FindClose(hFind); if( ! file.endsWith(realFileName, Qt::CaseSensitive) ) { - qDebug() << Q_FUNC_INFO << "Detected case clash between" << file << "and" << realFileName; + qCDebug(lcPropagator) << "Detected case clash between" << file << "and" << realFileName; re = true; } } @@ -621,7 +622,7 @@ bool OwncloudPropagator::hasCaseClashAccessibilityProblem(const QString &relfile if (firstFile != secondFile && QString::compare(firstFile, secondFile, Qt::CaseInsensitive) == 0) { result = true; - qDebug() << "Found two filepaths that only differ in case: " << firstFile << secondFile; + qCDebug(lcPropagator) << "Found two filepaths that only differ in case: " << firstFile << secondFile; } } FindClose(hFind); @@ -666,7 +667,7 @@ void OwncloudPropagator::scheduleNextJobImpl() } } if (_activeJobList.count() < maximumActiveTransferJob() + likelyFinishedQuicklyCount) { - qDebug() << "Can pump in another request! activeJobs =" << _activeJobList.count(); + qCDebug(lcPropagator) << "Can pump in another request! activeJobs =" << _activeJobList.count(); if (_rootJob->scheduleSelfOrChild()) { scheduleNextJob(); } @@ -769,7 +770,7 @@ bool PropagatorCompositeJob::scheduleSelfOrChild() _tasksToDo.remove(0); PropagatorJob *job = propagator()->createJob(nextTask); if (!job) { - qWarning() << "Useless task found for file" << nextTask->destination() << "instruction" << nextTask->_instruction; + qCWarning(lcDirectory) << "Useless task found for file" << nextTask->destination() << "instruction" << nextTask->_instruction; continue; } @@ -927,7 +928,7 @@ void PropagateDirectory::slotSubJobsFinished(SyncFileItem::Status status) if (!ok) { status = _item->_status = SyncFileItem::FatalError; _item->_errorString = tr("Error writing metadata to the database"); - qWarning() << "Error writing to the database for file" << _item->_file; + qCWarning(lcDirectory) << "Error writing to the database for file" << _item->_file; } } } @@ -968,10 +969,10 @@ void CleanupPollsJob::slotPollFinished() deleteLater(); return; } else if (job->_item->_status != SyncFileItem::Success) { - qDebug() << "There was an error with file " << job->_item->_file << job->_item->_errorString; + qCDebug(lcCleanupPolls) << "There was an error with file " << job->_item->_file << job->_item->_errorString; } else { if (!_journal->setFileRecord(SyncJournalFileRecord(*job->_item, _localPath + job->_item->_file))) { - qWarning() << "database error"; + qCWarning(lcCleanupPolls) << "database error"; job->_item->_status = SyncFileItem::FatalError; job->_item->_errorString = tr("Error writing metadata to the database"); emit aborted(job->_item->_errorString); diff --git a/src/libsync/owncloudpropagator.h b/src/libsync/owncloudpropagator.h index 461105000..beae46c2e 100644 --- a/src/libsync/owncloudpropagator.h +++ b/src/libsync/owncloudpropagator.h @@ -33,6 +33,8 @@ namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcPropagator) + /** Free disk space threshold below which syncs will abort and not even start. */ qint64 criticalFreeSpaceLimit(); diff --git a/src/libsync/owncloudpropagator_p.h b/src/libsync/owncloudpropagator_p.h index 3b188a2ef..f68dc7b0b 100644 --- a/src/libsync/owncloudpropagator_p.h +++ b/src/libsync/owncloudpropagator_p.h @@ -15,9 +15,10 @@ #pragma once -#include -#include +#include "owncloudpropagator.h" #include "syncfileitem.h" +#include +#include namespace OCC { @@ -48,7 +49,7 @@ inline QByteArray getEtagFromReply(QNetworkReply *reply) ret = etag; } if (ocEtag.length() > 0 && ocEtag != etag) { - qDebug() << "Quite peculiar, we have an etag != OC-Etag [no problem!]" << etag << ocEtag; + qCDebug(lcPropagator) << "Quite peculiar, we have an etag != OC-Etag [no problem!]" << etag << ocEtag; } return ret; } diff --git a/src/libsync/owncloudtheme.cpp b/src/libsync/owncloudtheme.cpp index 7b3805707..db3a1ad1f 100644 --- a/src/libsync/owncloudtheme.cpp +++ b/src/libsync/owncloudtheme.cpp @@ -23,7 +23,6 @@ #include #endif #include -#include #include "version.h" #include "config.h" @@ -34,7 +33,6 @@ namespace OCC { ownCloudTheme::ownCloudTheme() : Theme() { - // qDebug() << " ** running ownCloud theme!"; } QString ownCloudTheme::configFileName() const diff --git a/src/libsync/ownsql.cpp b/src/libsync/ownsql.cpp index 7008ccf52..92e32a8e5 100644 --- a/src/libsync/ownsql.cpp +++ b/src/libsync/ownsql.cpp @@ -14,8 +14,8 @@ #include +#include #include -#include #include #include #include @@ -33,6 +33,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcSql, "sync.database.sql", QtInfoMsg) + SqlDatabase::SqlDatabase() :_db(0), _errId(0) @@ -56,13 +58,13 @@ bool SqlDatabase::openHelper( const QString& filename, int sqliteFlags ) SQLITE_DO( sqlite3_open_v2(filename.toUtf8().constData(), &_db, sqliteFlags, 0) ); if( _errId != SQLITE_OK ) { - qDebug() << "Error:" << _error << "for" << filename; + qCDebug(lcSql) << "Error:" << _error << "for" << filename; close(); return false; } if( !_db ) { - qDebug() << "Error: no database for" << filename; + qCDebug(lcSql) << "Error: no database for" << filename; return false; } @@ -77,14 +79,14 @@ bool SqlDatabase::checkDb() SqlQuery quick_check(*this); quick_check.prepare("PRAGMA quick_check;", /*allow_failure=*/true); if( !quick_check.exec() ) { - qDebug() << "Error running quick_check on database"; + qCDebug(lcSql) << "Error running quick_check on database"; return false; } quick_check.next(); QString result = quick_check.stringValue(0); if( result != "ok" ) { - qDebug() << "quick_check returned failure:" << result; + qCDebug(lcSql) << "quick_check returned failure:" << result; return false; } @@ -105,12 +107,12 @@ bool SqlDatabase::openOrCreateReadWrite( const QString& filename ) // When disk space is low, checking the db may fail even though it's fine. qint64 freeSpace = Utility::freeDiskSpace(QFileInfo(filename).dir().absolutePath()); if (freeSpace != -1 && freeSpace < 1000000) { - qDebug() << "Consistency check failed, disk space is low, aborting" << freeSpace; + qCDebug(lcSql) << "Consistency check failed, disk space is low, aborting" << freeSpace; close(); return false; } - qDebug() << "Consistency check failed, removing broken db" << filename; + qCDebug(lcSql) << "Consistency check failed, removing broken db" << filename; close(); QFile::remove(filename); @@ -131,7 +133,7 @@ bool SqlDatabase::openReadOnly( const QString& filename ) } if( !checkDb() ) { - qDebug() << "Consistency check failed in readonly mode, giving up" << filename; + qCDebug(lcSql) << "Consistency check failed in readonly mode, giving up" << filename; close(); return false; } @@ -223,7 +225,7 @@ int SqlQuery::prepare( const QString& sql, bool allow_failure ) if( _errId != SQLITE_OK ) { _error = QString::fromUtf8(sqlite3_errmsg(_db)); - qWarning() << "Sqlite prepare statement error:" << _error << "in" <<_sql; + qCWarning(lcSql) << "Sqlite prepare statement error:" << _error << "in" <<_sql; ENFORCE(allow_failure, "SQLITE Prepare error"); } } @@ -264,7 +266,7 @@ bool SqlQuery::exec() if (_errId != SQLITE_DONE && _errId != SQLITE_ROW) { _error = QString::fromUtf8(sqlite3_errmsg(_db)); - qDebug() << "Sqlite exec statement error:" << _errId << _error << "in" <<_sql; + qCDebug(lcSql) << "Sqlite exec statement error:" << _errId << _error << "in" <<_sql; } return (_errId == SQLITE_DONE); // either SQLITE_ROW or SQLITE_DONE } @@ -335,7 +337,7 @@ void SqlQuery::bindValue(int pos, const QVariant& value) break; } } if (res != SQLITE_OK) { - qDebug() << Q_FUNC_INFO << "ERROR" << value << res; + qCDebug(lcSql) << "ERROR" << value << res; } ASSERT( res == SQLITE_OK ); } diff --git a/src/libsync/progressdispatcher.cpp b/src/libsync/progressdispatcher.cpp index a2cbb688a..6ed274730 100644 --- a/src/libsync/progressdispatcher.cpp +++ b/src/libsync/progressdispatcher.cpp @@ -16,7 +16,6 @@ #include #include -#include #include namespace OCC { diff --git a/src/libsync/progressdispatcher.h b/src/libsync/progressdispatcher.h index 4571ed947..47d6d1b3c 100644 --- a/src/libsync/progressdispatcher.h +++ b/src/libsync/progressdispatcher.h @@ -22,7 +22,6 @@ #include #include #include -#include #include "syncfileitem.h" diff --git a/src/libsync/propagatedownload.cpp b/src/libsync/propagatedownload.cpp index 893f40502..2a4acf465 100644 --- a/src/libsync/propagatedownload.cpp +++ b/src/libsync/propagatedownload.cpp @@ -25,10 +25,10 @@ #include "checksums.h" #include "asserts.h" +#include #include #include #include -#include #include #ifdef Q_OS_UNIX @@ -37,6 +37,9 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcGetFile, "sync.networkjob.get", QtInfoMsg) +Q_LOGGING_CATEGORY(lcPropagateDownload, "sync.propagator.download", QtInfoMsg) + // Always coming in with forward slashes. // In csync_excluded_no_ctx we ignore all files with longer than 254 chars // This function also adds a dot at the beginning of the filename to hide the file on OS X and Linux @@ -90,7 +93,7 @@ void GETFileJob::start() { if (_resumeStart > 0) { _headers["Range"] = "bytes=" + QByteArray::number(_resumeStart) +'-'; _headers["Accept-Ranges"] = "bytes"; - qDebug() << "Retry with range " << _headers["Range"]; + qCDebug(lcGetFile) << "Retry with range " << _headers["Range"]; } QNetworkRequest req; @@ -106,13 +109,13 @@ void GETFileJob::start() { } reply()->setReadBufferSize(16 * 1024); // keep low so we can easier limit the bandwidth - qDebug() << Q_FUNC_INFO << _bandwidthManager << _bandwidthChoked << _bandwidthLimited; + qCDebug(lcGetFile) << _bandwidthManager << _bandwidthChoked << _bandwidthLimited; if (_bandwidthManager) { _bandwidthManager->registerDownloadJob(this); } if( reply()->error() != QNetworkReply::NoError ) { - qWarning() << Q_FUNC_INFO << " Network error: " << errorString(); + qCWarning(lcGetFile) << " Network error: " << errorString(); } connect(reply(), SIGNAL(metaDataChanged()), this, SLOT(slotMetaDataChanged())); @@ -143,18 +146,18 @@ void GETFileJob::slotMetaDataChanged() _etag = getEtagFromReply(reply()); if (!_directDownloadUrl.isEmpty() && !_etag.isEmpty()) { - qDebug() << Q_FUNC_INFO << "Direct download used, ignoring server ETag" << _etag; + qCDebug(lcGetFile) << "Direct download used, ignoring server ETag" << _etag; _etag = QByteArray(); // reset received ETag } else if (!_directDownloadUrl.isEmpty()) { // All fine, ETag empty and directDownloadUrl used } else if (_etag.isEmpty()) { - qDebug() << Q_FUNC_INFO << "No E-Tag reply by server, considering it invalid"; + qCDebug(lcGetFile) << "No E-Tag reply by server, considering it invalid"; _errorString = tr("No E-Tag received from server, check Proxy/Gateway"); _errorStatus = SyncFileItem::NormalError; reply()->abort(); return; } else if (!_expectedEtagForResume.isEmpty() && _expectedEtagForResume != _etag) { - qDebug() << Q_FUNC_INFO << "We received a different E-Tag for resuming!" + qCDebug(lcGetFile) << "We received a different E-Tag for resuming!" << _expectedEtagForResume << "vs" << _etag; _errorString = tr("We received a different E-Tag for resuming. Retrying next time."); _errorStatus = SyncFileItem::NormalError; @@ -171,7 +174,7 @@ void GETFileJob::slotMetaDataChanged() } } if (start != _resumeStart) { - qDebug() << Q_FUNC_INFO << "Wrong content-range: "<< ranges << " while expecting start was" << _resumeStart; + qCDebug(lcGetFile) << "Wrong content-range: "<< ranges << " while expecting start was" << _resumeStart; if (ranges.isEmpty()) { // device doesn't support range, just try again from scratch _device->close(); @@ -216,7 +219,7 @@ void GETFileJob::setBandwidthLimited(bool b) void GETFileJob::giveBandwidthQuota(qint64 q) { _bandwidthQuota = q; - qDebug() << Q_FUNC_INFO << "Got" << q << "bytes"; + qCDebug(lcGetFile) << "Got" << q << "bytes"; QMetaObject::invokeMethod(this, "slotReadyRead", Qt::QueuedConnection); } @@ -235,29 +238,26 @@ void GETFileJob::slotReadyRead() int bufferSize = qMin(1024*8ll , reply()->bytesAvailable()); QByteArray buffer(bufferSize, Qt::Uninitialized); - //qDebug() << Q_FUNC_INFO << reply()->bytesAvailable() << reply()->isOpen() << reply()->isFinished(); - while(reply()->bytesAvailable() > 0) { if (_bandwidthChoked) { - qDebug() << Q_FUNC_INFO << "Download choked"; + qCDebug(lcGetFile) << "Download choked"; break; } qint64 toRead = bufferSize; if (_bandwidthLimited) { toRead = qMin(qint64(bufferSize), _bandwidthQuota); if (toRead == 0) { - //qDebug() << Q_FUNC_INFO << "Out of quota"; + qCDebug(lcGetFile) << "Out of quota"; break; } _bandwidthQuota -= toRead; - //qDebug() << Q_FUNC_INFO << "Reading" << toRead << "remaining" << _bandwidthQuota; } qint64 r = reply()->read(buffer.data(), toRead); if (r < 0) { _errorString = networkReplyErrorString(*reply()); _errorStatus = SyncFileItem::NormalError; - qDebug() << "Error while reading from device: " << _errorString; + qCDebug(lcGetFile) << "Error while reading from device: " << _errorString; reply()->abort(); return; } @@ -267,16 +267,15 @@ void GETFileJob::slotReadyRead() if (w != r) { _errorString = _device->errorString(); _errorStatus = SyncFileItem::NormalError; - qDebug() << "Error while writing to file" << w << r << _errorString; + qCDebug(lcGetFile) << "Error while writing to file" << w << r << _errorString; reply()->abort(); return; } } } - //qDebug() << Q_FUNC_INFO << "END" << reply()->isFinished() << reply()->bytesAvailable() << _hasEmittedFinishedSignal; if (reply()->isFinished() && reply()->bytesAvailable() == 0) { - qDebug() << Q_FUNC_INFO << "Actually finished!"; + qCDebug(lcGetFile) << "Actually finished!"; if (_bandwidthManager) { _bandwidthManager->unregisterDownloadJob(this); } @@ -290,7 +289,7 @@ void GETFileJob::slotReadyRead() void GETFileJob::onTimedOut() { - qDebug() << "Timeout" << (reply() ? reply()->request().url() : path()); + qCDebug(lcGetFile) << "Timeout" << (reply() ? reply()->request().url() : path()); if (!reply()) return; _errorString = tr("Connection Timeout"); @@ -311,7 +310,7 @@ void PropagateDownloadFile::start() if (propagator()->_abortRequested.fetchAndAddRelaxed(0)) return; - qDebug() << Q_FUNC_INFO << _item->_file << propagator()->_activeJobList.count(); + qCDebug(lcPropagateDownload) << _item->_file << propagator()->_activeJobList.count(); _stopwatch.start(); if (_deleteExisting) { @@ -362,7 +361,7 @@ void PropagateDownloadFile::start() _resumeStart = _tmpFile.size(); if (_resumeStart > 0) { if (_resumeStart == _item->_size) { - qDebug() << "File is already complete, no need to download"; + qCDebug(lcPropagateDownload) << "File is already complete, no need to download"; _tmpFile.close(); downloadFinished(); return; @@ -409,7 +408,7 @@ void PropagateDownloadFile::start() &_tmpFile, headers, expectedEtagForResume, _resumeStart, this); } else { // We were provided a direct URL, use that one - qDebug() << Q_FUNC_INFO << "directDownloadUrl given for " << _item->_file << _item->_directDownloadUrl; + qCDebug(lcPropagateDownload) << "directDownloadUrl given for " << _item->_file << _item->_directDownloadUrl; if (!_item->_directDownloadCookies.isEmpty()) { headers["Cookie"] = _item->_directDownloadCookies.toUtf8(); @@ -448,7 +447,7 @@ void PropagateDownloadFile::slotGetFinished() GETFileJob *job = qobject_cast(sender()); ASSERT(job); - qDebug() << Q_FUNC_INFO << job->reply()->request().url() << "FINISHED WITH STATUS" + qCDebug(lcPropagateDownload) << job->reply()->request().url() << "FINISHED WITH STATUS" << job->reply()->error() << (job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : job->errorString()) << _item->_httpErrorCode @@ -463,14 +462,14 @@ void PropagateDownloadFile::slotGetFinished() // without the header. const bool badRangeHeader = job->resumeStart() > 0 && _item->_httpErrorCode == 416; if (badRangeHeader) { - qDebug() << Q_FUNC_INFO << "server replied 416 to our range request, trying again without"; + qCDebug(lcPropagateDownload) << "server replied 416 to our range request, trying again without"; propagator()->_anotherSyncNeeded = true; } // Getting a 404 probably means that the file was deleted on the server. const bool fileNotFound = _item->_httpErrorCode == 404; if (fileNotFound) { - qDebug() << Q_FUNC_INFO << "server replied 404, assuming file was deleted"; + qCDebug(lcPropagateDownload) << "server replied 404, assuming file was deleted"; } // Don't keep the temporary file if it is empty or we @@ -483,7 +482,7 @@ void PropagateDownloadFile::slotGetFinished() if(!_item->_directDownloadUrl.isEmpty() && err != QNetworkReply::OperationCanceledError) { // If this was with a direct download, retry without direct download - qWarning() << "Direct download of" << _item->_directDownloadUrl << "failed. Retrying through owncloud."; + qCWarning(lcPropagateDownload) << "Direct download of" << _item->_directDownloadUrl << "failed. Retrying through owncloud."; _item->_directDownloadUrl.clear(); start(); return; @@ -540,14 +539,14 @@ void PropagateDownloadFile::slotGetFinished() if (!job->reply()->rawHeader(sizeHeader).isEmpty() && _tmpFile.size() > 0 && bodySize == 0) { // Strange bug with broken webserver or webfirewall https://github.com/owncloud/client/issues/3373#issuecomment-122672322 // This happened when trying to resume a file. The Content-Range header was files, Content-Length was == 0 - qDebug() << bodySize << _item->_size << _tmpFile.size() << job->resumeStart(); + qCDebug(lcPropagateDownload) << bodySize << _item->_size << _tmpFile.size() << job->resumeStart(); FileSystem::remove(_tmpFile.fileName()); done(SyncFileItem::SoftError, QLatin1String("Broken webserver returning empty content length for non-empty file on resume")); return; } if(bodySize > 0 && bodySize != _tmpFile.size() - job->resumeStart() ) { - qDebug() << bodySize << _tmpFile.size() << job->resumeStart(); + qCDebug(lcPropagateDownload) << bodySize << _tmpFile.size() << job->resumeStart(); propagator()->_anotherSyncNeeded = true; done(SyncFileItem::SoftError, tr("The file could not be downloaded completely.")); return; @@ -626,13 +625,13 @@ static QString makeRecallFileName(const QString &fn) void handleRecallFile(const QString& filePath, const QString& folderPath, SyncJournalDb& journal) { - qDebug() << "handleRecallFile: " << filePath; + qCDebug(lcPropagateDownload) << "handleRecallFile: " << filePath; FileSystem::setFileHidden(filePath, true); QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { - qWarning() << "Could not open recall file" << file.errorString(); + qCWarning(lcPropagateDownload) << "Could not open recall file" << file.errorString(); return; } QFileInfo existingFile(filePath); @@ -644,7 +643,7 @@ void handleRecallFile(const QString& filePath, const QString& folderPath, SyncJo QString recalledFile = QDir::cleanPath(baseDir.filePath(line)); if (!recalledFile.startsWith(folderPath) || !recalledFile.startsWith(baseDir.path())) { - qDebug() << "Ignoring recall of " << recalledFile; + qCDebug(lcPropagateDownload) << "Ignoring recall of " << recalledFile; continue; } @@ -653,15 +652,15 @@ void handleRecallFile(const QString& filePath, const QString& folderPath, SyncJo SyncJournalFileRecord record = journal.getFileRecord(localRecalledFile); if (!record.isValid()) { - qDebug() << "No db entry for recall of" << localRecalledFile; + qCDebug(lcPropagateDownload) << "No db entry for recall of" << localRecalledFile; continue; } - qDebug() << "Recalling" << localRecalledFile << "Checksum:" << record._contentChecksumType << record._contentChecksum; + qCDebug(lcPropagateDownload) << "Recalling" << localRecalledFile << "Checksum:" << record._contentChecksumType << record._contentChecksum; QString targetPath = makeRecallFileName(recalledFile); - qDebug() << "Copy recall file: " << recalledFile << " -> " << targetPath; + qCDebug(lcPropagateDownload) << "Copy recall file: " << recalledFile << " -> " << targetPath; // Remove the target first, QFile::copy will not overwrite it. FileSystem::remove(targetPath); QFile::copy(recalledFile, targetPath); @@ -740,7 +739,7 @@ void PropagateDownloadFile::downloadFinished() done(SyncFileItem::SoftError, renameError); return; } - qDebug() << "Created conflict file" << fn << "->" << conflictFileName; + qCDebug(lcPropagateDownload) << "Created conflict file" << fn << "->" << conflictFileName; } FileSystem::setModTime(_tmpFile.fileName(), _item->_modtime); @@ -782,7 +781,7 @@ void PropagateDownloadFile::downloadFinished() emit propagator()->touchedFile(fn); // The fileChanged() check is done above to generate better error messages. if (!FileSystem::uncheckedRenameReplace(_tmpFile.fileName(), fn, &error)) { - qDebug() << Q_FUNC_INFO << QString("Rename failed: %1 => %2").arg(_tmpFile.fileName()).arg(fn); + qCDebug(lcPropagateDownload) << QString("Rename failed: %1 => %2").arg(_tmpFile.fileName()).arg(fn); // If we moved away the original file due to a conflict but can't // put the downloaded file in its place, we are in a bad spot: @@ -830,7 +829,7 @@ void PropagateDownloadFile::downloadFinished() qint64 duration = _stopwatch.elapsed(); if (isLikelyFinishedQuickly() && duration > 5*1000) { - qDebug() << "WARNING: Unexpectedly slow connection, took" << duration << "msec for" << _item->_size - _resumeStart << "bytes for" << _item->_file; + qCDebug(lcPropagateDownload) << "WARNING: Unexpectedly slow connection, took" << duration << "msec for" << _item->_size - _resumeStart << "bytes for" << _item->_file; } } diff --git a/src/libsync/propagatedownload.h b/src/libsync/propagatedownload.h index 437e7a514..6e4cad115 100644 --- a/src/libsync/propagatedownload.h +++ b/src/libsync/propagatedownload.h @@ -59,9 +59,7 @@ public: virtual void start() Q_DECL_OVERRIDE; virtual bool finished() Q_DECL_OVERRIDE { -// qDebug() << Q_FUNC_INFO << reply()->bytesAvailable() << _hasEmittedFinishedSignal; if (reply()->bytesAvailable()) { -// qDebug() << Q_FUNC_INFO << "Not all read yet because of bandwidth limits"; return false; } else { if (_bandwidthManager) { diff --git a/src/libsync/propagateremotedelete.cpp b/src/libsync/propagateremotedelete.cpp index 634f31ac6..c8bc87a24 100644 --- a/src/libsync/propagateremotedelete.cpp +++ b/src/libsync/propagateremotedelete.cpp @@ -17,8 +17,13 @@ #include "account.h" #include "asserts.h" +#include + namespace OCC { +Q_LOGGING_CATEGORY(lcDeleteJob, "sync.networkjob.delete", QtInfoMsg) +Q_LOGGING_CATEGORY(lcPropagateRemoteDelete, "sync.propagator.remotedelete", QtInfoMsg) + DeleteJob::DeleteJob(AccountPtr account, const QString& path, QObject* parent) : AbstractNetworkJob(account, path, parent) { } @@ -37,7 +42,7 @@ void DeleteJob::start() } if( reply()->error() != QNetworkReply::NoError ) { - qWarning() << Q_FUNC_INFO << " Network error: " << reply()->errorString(); + qCWarning(lcDeleteJob) << " Network error: " << reply()->errorString(); } AbstractNetworkJob::start(); } @@ -53,7 +58,7 @@ void PropagateRemoteDelete::start() if (propagator()->_abortRequested.fetchAndAddRelaxed(0)) return; - qDebug() << Q_FUNC_INFO << _item->_file; + qCDebug(lcPropagateRemoteDelete) << _item->_file; _job = new DeleteJob(propagator()->account(), propagator()->_remoteFolder + _item->_file, @@ -75,7 +80,7 @@ void PropagateRemoteDelete::slotDeleteJobFinished() ASSERT(_job); - qDebug() << Q_FUNC_INFO << _job->reply()->request().url() << "FINISHED WITH STATUS" + qCDebug(lcPropagateRemoteDelete) << _job->reply()->request().url() << "FINISHED WITH STATUS" << _job->reply()->error() << (_job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : _job->errorString()); diff --git a/src/libsync/propagateremotemkdir.cpp b/src/libsync/propagateremotemkdir.cpp index cb4673888..a6db2c2d7 100644 --- a/src/libsync/propagateremotemkdir.cpp +++ b/src/libsync/propagateremotemkdir.cpp @@ -18,16 +18,20 @@ #include "syncjournalfilerecord.h" #include "propagateremotedelete.h" #include "asserts.h" + #include +#include namespace OCC { +Q_LOGGING_CATEGORY(lcPropagateRemoteMkdir, "sync.propagator.remotemkdir", QtInfoMsg) + void PropagateRemoteMkdir::start() { if (propagator()->_abortRequested.fetchAndAddRelaxed(0)) return; - qDebug() << Q_FUNC_INFO << _item->_file; + qCDebug(lcPropagateRemoteMkdir) << _item->_file; propagator()->_activeJobList.append(this); @@ -47,7 +51,7 @@ void PropagateRemoteMkdir::slotStartMkcolJob() if (propagator()->_abortRequested.fetchAndAddRelaxed(0)) return; - qDebug() << Q_FUNC_INFO << _item->_file; + qCDebug(lcPropagateRemoteMkdir) << _item->_file; _job = new MkColJob(propagator()->account(), propagator()->_remoteFolder + _item->_file, @@ -73,7 +77,7 @@ void PropagateRemoteMkdir::slotMkcolJobFinished() ASSERT(_job); - qDebug() << Q_FUNC_INFO << _job->reply()->request().url() << "FINISHED WITH STATUS" + qCDebug(lcPropagateRemoteMkdir) << _job->reply()->request().url() << "FINISHED WITH STATUS" << _job->reply()->error() << (_job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : _job->errorString()); diff --git a/src/libsync/propagateremotemove.cpp b/src/libsync/propagateremotemove.cpp index f2410fb76..a7d5b5162 100644 --- a/src/libsync/propagateremotemove.cpp +++ b/src/libsync/propagateremotemove.cpp @@ -25,6 +25,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcPropagateRemoteMove, "sync.propagator.remotemove", QtInfoMsg) + MoveJob::MoveJob(AccountPtr account, const QString& path, const QString &destination, QObject* parent) : AbstractNetworkJob(account, path, parent), _destination(destination) @@ -50,7 +52,7 @@ void MoveJob::start() } if( reply()->error() != QNetworkReply::NoError ) { - qWarning() << Q_FUNC_INFO << " Network error: " << reply()->errorString(); + qCWarning(lcPropagateRemoteMove) << " Network error: " << reply()->errorString(); } AbstractNetworkJob::start(); } @@ -67,7 +69,7 @@ void PropagateRemoteMove::start() if (propagator()->_abortRequested.fetchAndAddRelaxed(0)) return; - qDebug() << Q_FUNC_INFO << _item->_file << _item->_renameTarget; + qCDebug(lcPropagateRemoteMove) << _item->_file << _item->_renameTarget; QString targetFile(propagator()->getFilePath(_item->_renameTarget)); @@ -118,7 +120,7 @@ void PropagateRemoteMove::slotMoveJobFinished() ASSERT(_job); - qDebug() << Q_FUNC_INFO << _job->reply()->request().url() << "FINISHED WITH STATUS" + qCDebug(lcPropagateRemoteMove) << _job->reply()->request().url() << "FINISHED WITH STATUS" << _job->reply()->error() << (_job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : _job->errorString()); @@ -169,7 +171,7 @@ void PropagateRemoteMove::finalize() record._contentChecksum = oldRecord._contentChecksum; record._contentChecksumType = oldRecord._contentChecksumType; if (record._fileSize != oldRecord._fileSize) { - qDebug() << "Warning: file sizes differ on server vs sync journal: " << record._fileSize << oldRecord._fileSize; + qCDebug(lcPropagateRemoteMove) << "Warning: file sizes differ on server vs sync journal: " << record._fileSize << oldRecord._fileSize; record._fileSize = oldRecord._fileSize; // server might have claimed different size, we take the old one from the DB } } diff --git a/src/libsync/propagateupload.cpp b/src/libsync/propagateupload.cpp index e5f693995..2713d560c 100644 --- a/src/libsync/propagateupload.cpp +++ b/src/libsync/propagateupload.cpp @@ -43,6 +43,10 @@ const char owncloudShouldSoftCancelPropertyName[] = "owncloud-should-soft-cancel namespace OCC { +Q_LOGGING_CATEGORY(lcPutFile, "sync.networkjob.put", QtInfoMsg) +Q_LOGGING_CATEGORY(lcPoll, "sync.networkjob.poll", QtInfoMsg) +Q_LOGGING_CATEGORY(lcPropagateUpload, "sync.propagator.upload", QtInfoMsg) + /** * We do not want to upload files that are currently being modified. * To avoid that, we don't upload files that have a modification time @@ -81,7 +85,7 @@ void PUTFileJob::start() { } if( reply()->error() != QNetworkReply::NoError ) { - qWarning() << Q_FUNC_INFO << " Network error: " << reply()->errorString(); + qCWarning(lcPutFile) << " Network error: " << reply()->errorString(); } connect(reply(), SIGNAL(uploadProgress(qint64,qint64)), this, SIGNAL(uploadProgress(qint64,qint64))); @@ -143,7 +147,7 @@ bool PollJob::finished() } QByteArray jsonData = reply()->readAll().trimmed(); - qDebug() << Q_FUNC_INFO << ">" << jsonData << "<" << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + qCDebug(lcPoll) << ">" << jsonData << "<" << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QJsonParseError jsonParseError; QJsonObject status = QJsonDocument::fromJson(jsonData, &jsonParseError).object(); if (jsonParseError.error != QJsonParseError::NoError) { @@ -376,7 +380,6 @@ qint64 UploadDevice::writeData(const char* , qint64 ) { } qint64 UploadDevice::readData(char* data, qint64 maxlen) { - //qDebug() << Q_FUNC_INFO << maxlen << _read << _size << _bandwidthQuota; if (_data.size() - _read <= 0) { // at end if (_bandwidthManager) { @@ -394,7 +397,6 @@ qint64 UploadDevice::readData(char* data, qint64 maxlen) { if (isBandwidthLimited()) { maxlen = qMin(maxlen, _bandwidthQuota); if (maxlen <= 0) { // no quota - //qDebug() << "no quota"; return 0; } _bandwidthQuota -= maxlen; @@ -406,7 +408,6 @@ qint64 UploadDevice::readData(char* data, qint64 maxlen) { void UploadDevice::slotJobUploadProgress(qint64 sent, qint64 t) { - //qDebug() << Q_FUNC_INFO << sent << _read << t << _size << _bandwidthQuota; if (sent == 0 || t == 0) { return; } @@ -418,14 +419,11 @@ bool UploadDevice::atEnd() const { } qint64 UploadDevice::size() const{ -// qDebug() << this << Q_FUNC_INFO << _size; return _data.size(); } qint64 UploadDevice::bytesAvailable() const { -// qDebug() << this << Q_FUNC_INFO << _size << _read << QIODevice::bytesAvailable() -// << _size - _read + QIODevice::bytesAvailable(); return _data.size() - _read + QIODevice::bytesAvailable(); } @@ -503,11 +501,11 @@ void PropagateUploadFileCommon::checkResettingErrors() auto uploadInfo = propagator()->_journal->getUploadInfo(_item->_file); uploadInfo._errorCount += 1; if (uploadInfo._errorCount > 3) { - qDebug() << "Reset transfer of" << _item->_file + qCDebug(lcPropagateUpload) << "Reset transfer of" << _item->_file << "due to repeated error" << _item->_httpErrorCode; uploadInfo = SyncJournalDb::UploadInfo(); } else { - qDebug() << "Error count for maybe-reset error" << _item->_httpErrorCode + qCDebug(lcPropagateUpload) << "Error count for maybe-reset error" << _item->_httpErrorCode << "on file" << _item->_file << "is" << uploadInfo._errorCount; } @@ -525,7 +523,7 @@ void PropagateUploadFileCommon::abort() { foreach(auto *job, _jobs) { if (job->reply()) { - qDebug() << Q_FUNC_INFO << job << this->_item->_file; + qCDebug(lcPropagateUpload) << job << this->_item->_file; job->reply()->abort(); } } diff --git a/src/libsync/propagateupload.h b/src/libsync/propagateupload.h index bebd70dce..a7a73dcbe 100644 --- a/src/libsync/propagateupload.h +++ b/src/libsync/propagateupload.h @@ -18,11 +18,13 @@ #include #include -#include #include namespace OCC { + +Q_DECLARE_LOGGING_CATEGORY(lcPropagateUpload) + class BandwidthManager; /** diff --git a/src/libsync/propagateuploadng.cpp b/src/libsync/propagateuploadng.cpp index f646797bb..61985f40c 100644 --- a/src/libsync/propagateuploadng.cpp +++ b/src/libsync/propagateuploadng.cpp @@ -139,17 +139,17 @@ void PropagateUploadFileNG::slotPropfindFinished() if (_sent > _item->_size) { // Normally this can't happen because the size is xor'ed with the transfer id, and it is // therefore impossible that there is more data on the server than on the file. - qWarning() << "Inconsistency while resuming " << _item->_file + qCWarning(lcPropagateUpload) << "Inconsistency while resuming " << _item->_file << ": the size on the server (" << _sent << ") is bigger than the size of the file (" << _item->_size << ")"; startNewUpload(); return; } - qDebug() << "Resuming "<< _item->_file << " from chunk " << _currentChunk << "; sent ="<< _sent; + qCDebug(lcPropagateUpload) << "Resuming "<< _item->_file << " from chunk " << _currentChunk << "; sent ="<< _sent; if (!_serverChunks.isEmpty()) { - qDebug() << "To Delete" << _serverChunks.keys(); + qCDebug(lcPropagateUpload) << "To Delete" << _serverChunks.keys(); propagator()->_activeJobList.append(this); _removeJobError = false; @@ -198,7 +198,7 @@ void PropagateUploadFileNG::slotDeleteJobFinished() abortWithError(status, job->errorString()); return; } else { - qWarning() << "DeleteJob errored out" << job->errorString() << job->reply()->url(); + qCWarning(lcPropagateUpload) << "DeleteJob errored out" << job->errorString() << job->reply()->url(); _removeJobError = true; // Let the other jobs finish } @@ -304,7 +304,7 @@ void PropagateUploadFileNG::startNextChunk() const QString fileName = propagator()->getFilePath(_item->_file); if (! device->prepareAndOpen(fileName, _sent, _currentChunkSize)) { - qDebug() << "ERR: Could not prepare upload device: " << device->errorString(); + qCDebug(lcPropagateUpload) << "ERR: Could not prepare upload device: " << device->errorString(); // If the file is currently locked, we want to retry the sync // when it becomes available again. @@ -346,7 +346,7 @@ void PropagateUploadFileNG::slotPutFinished() slotJobDestroyed(job); // remove it from the _jobs list - qDebug() << job->reply()->request().url() << "FINISHED WITH STATUS" + qCDebug(lcPropagateUpload) << job->reply()->request().url() << "FINISHED WITH STATUS" << job->reply()->error() << (job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : job->errorString()) << job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute) @@ -365,7 +365,7 @@ void PropagateUploadFileNG::slotPutFinished() if (err == QNetworkReply::OperationCanceledError && job->reply()->property("owncloud-should-soft-cancel").isValid()) { // Abort the job and try again later. // This works around a bug in QNAM wich might reuse a non-empty buffer for the next request. - qDebug() << "Forcing job abort on HTTP connection reset with Qt < 5.4.2."; + qCDebug(lcPropagateUpload) << "Forcing job abort on HTTP connection reset with Qt < 5.4.2."; propagator()->_anotherSyncNeeded = true; abortWithError(SyncFileItem::SoftError, tr("Forcing job abort on HTTP connection reset with Qt < 5.4.2.")); return; @@ -376,7 +376,7 @@ void PropagateUploadFileNG::slotPutFinished() _item->_httpErrorCode = job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QByteArray replyContent; QString errorString = job->errorStringParsingBody(&replyContent); - qDebug() << replyContent; // display the XML error in the debug + qCDebug(lcPropagateUpload) << replyContent; // display the XML error in the debug // Ensure errors that should eventually reset the chunked upload are tracked. checkResettingErrors(); @@ -413,7 +413,7 @@ void PropagateUploadFileNG::slotPutFinished() targetSize, propagator()->syncOptions()._maxChunkSize); - qDebug() << "Chunked upload of" << _currentChunkSize << "bytes took" << uploadTime + qCDebug(lcPropagateUpload) << "Chunked upload of" << _currentChunkSize << "bytes took" << uploadTime << "ms, desired is" << targetDuration << "ms, expected good chunk size is" << predictedGoodSize << "bytes and nudged next chunk size to " << propagator()->_chunkSize << "bytes"; @@ -490,20 +490,20 @@ void PropagateUploadFileNG::slotMoveJobFinished() QByteArray fid = job->reply()->rawHeader("OC-FileID"); if(fid.isEmpty()) { - qWarning() << "Server did not return a OC-FileID" << _item->_file; + qCWarning(lcPropagateUpload) << "Server did not return a OC-FileID" << _item->_file; abortWithError(SyncFileItem::NormalError, tr("Missing File ID from server")); return; } else { // the old file id should only be empty for new files uploaded if( !_item->_fileId.isEmpty() && _item->_fileId != fid ) { - qDebug() << "WARN: File ID changed!" << _item->_fileId << fid; + qCDebug(lcPropagateUpload) << "WARN: File ID changed!" << _item->_fileId << fid; } _item->_fileId = fid; } _item->_etag = getEtagFromReply(job->reply());; if (_item->_etag.isEmpty()) { - qWarning() << "Server did not return an ETAG" << _item->_file; + qCWarning(lcPropagateUpload) << "Server did not return an ETAG" << _item->_file; abortWithError(SyncFileItem::NormalError, tr("Missing ETag from server")); return; } @@ -512,7 +512,7 @@ void PropagateUploadFileNG::slotMoveJobFinished() #ifdef WITH_TESTING // performance logging quint64 duration = _stopWatch.stop(); - qDebug() << "*==* duration UPLOAD" << _item->_size + qCDebug(lcPropagateUpload) << "*==* duration UPLOAD" << _item->_size << _stopWatch.durationOfLap(QLatin1String("ContentChecksum")) << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum")) << duration; diff --git a/src/libsync/propagateuploadv1.cpp b/src/libsync/propagateuploadv1.cpp index 946bdcbbe..1e90d297d 100644 --- a/src/libsync/propagateuploadv1.cpp +++ b/src/libsync/propagateuploadv1.cpp @@ -34,6 +34,7 @@ #include namespace OCC { + void PropagateUploadFileV1::doStartUpload() { _chunkCount = std::ceil(_item->_size / double(chunkSize())); @@ -45,7 +46,7 @@ void PropagateUploadFileV1::doStartUpload() if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime ) { _startChunk = progressInfo._chunk; _transferId = progressInfo._transferid; - qDebug() << Q_FUNC_INFO << _item->_file << ": Resuming from chunk " << _startChunk; + qCDebug(lcPropagateUpload) << _item->_file << ": Resuming from chunk " << _startChunk; } _currentChunk = 0; @@ -82,7 +83,7 @@ void PropagateUploadFileV1::startNextChunk() int sendingChunk = (_currentChunk + _startChunk) % _chunkCount; // XOR with chunk size to make sure everything goes well if chunk size changes between runs uint transid = _transferId ^ chunkSize(); - qDebug() << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid; + qCDebug(lcPropagateUpload) << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid; path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk); headers["OC-Chunked"] = "1"; @@ -100,7 +101,7 @@ void PropagateUploadFileV1::startNextChunk() // if there's only one chunk, it's the final one isFinalChunk = true; } - qDebug() << _chunkCount << isFinalChunk << chunkStart << currentChunkSize; + qCDebug(lcPropagateUpload) << _chunkCount << isFinalChunk << chunkStart << currentChunkSize; if (isFinalChunk && !_transmissionChecksumType.isEmpty()) { headers[checkSumHeaderC] = makeChecksumHeader( @@ -109,7 +110,7 @@ void PropagateUploadFileV1::startNextChunk() const QString fileName = propagator()->getFilePath(_item->_file); if (! device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) { - qDebug() << "ERR: Could not prepare upload device: " << device->errorString(); + qCDebug(lcPropagateUpload) << "ERR: Could not prepare upload device: " << device->errorString(); // If the file is currently locked, we want to retry the sync // when it becomes available again. @@ -175,7 +176,7 @@ void PropagateUploadFileV1::slotPutFinished() slotJobDestroyed(job); // remove it from the _jobs list - qDebug() << Q_FUNC_INFO << job->reply()->request().url() << "FINISHED WITH STATUS" + qCDebug(lcPropagateUpload) << job->reply()->request().url() << "FINISHED WITH STATUS" << job->reply()->error() << (job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : job->errorString()) << job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute) @@ -193,7 +194,7 @@ void PropagateUploadFileV1::slotPutFinished() #if QT_VERSION < QT_VERSION_CHECK(5, 4, 2) if (err == QNetworkReply::OperationCanceledError && job->reply()->property("owncloud-should-soft-cancel").isValid()) { // Abort the job and try again later. // This works around a bug in QNAM wich might reuse a non-empty buffer for the next request. - qDebug() << "Forcing job abort on HTTP connection reset with Qt < 5.4.2."; + qCDebug(lcPropagateUpload) << "Forcing job abort on HTTP connection reset with Qt < 5.4.2."; propagator()->_anotherSyncNeeded = true; abortWithError(SyncFileItem::SoftError, tr("Forcing job abort on HTTP connection reset with Qt < 5.4.2.")); return; @@ -209,7 +210,7 @@ void PropagateUploadFileV1::slotPutFinished() } QByteArray replyContent; QString errorString = job->errorStringParsingBody(&replyContent); - qDebug() << replyContent; // display the XML error in the debug + qCDebug(lcPropagateUpload) << replyContent; // display the XML error in the debug if (_item->_httpErrorCode == 412) { // Precondition Failed: Either an etag or a checksum mismatch. @@ -319,7 +320,7 @@ void PropagateUploadFileV1::slotPutFinished() QByteArray fid = job->reply()->rawHeader("OC-FileID"); if( !fid.isEmpty() ) { if( !_item->_fileId.isEmpty() && _item->_fileId != fid ) { - qDebug() << "WARN: File ID changed!" << _item->_fileId << fid; + qCDebug(lcPropagateUpload) << "WARN: File ID changed!" << _item->_fileId << fid; } _item->_fileId = fid; } @@ -331,7 +332,7 @@ void PropagateUploadFileV1::slotPutFinished() if (job->reply()->rawHeader("X-OC-MTime") != "accepted") { // X-OC-MTime is supported since owncloud 5.0. But not when chunking. // Normally Owncloud 6 always puts X-OC-MTime - qWarning() << "Server does not support X-OC-MTime" << job->reply()->rawHeader("X-OC-MTime"); + qCWarning(lcPropagateUpload) << "Server does not support X-OC-MTime" << job->reply()->rawHeader("X-OC-MTime"); // Well, the mtime was not set done(SyncFileItem::SoftError, "Server does not support X-OC-MTime"); } @@ -339,7 +340,7 @@ void PropagateUploadFileV1::slotPutFinished() #ifdef WITH_TESTING // performance logging quint64 duration = _stopWatch.stop(); - qDebug() << "*==* duration UPLOAD" << _item->_size + qCDebug(lcPropagateUpload) << "*==* duration UPLOAD" << _item->_size << _stopWatch.durationOfLap(QLatin1String("ContentChecksum")) << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum")) << duration; diff --git a/src/libsync/propagatorjobs.cpp b/src/libsync/propagatorjobs.cpp index 3827daeef..4cc8f5ec5 100644 --- a/src/libsync/propagatorjobs.cpp +++ b/src/libsync/propagatorjobs.cpp @@ -29,7 +29,6 @@ #else #include #endif -#include #include #include #include @@ -39,6 +38,10 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcPropagateLocalRemove, "sync.propagator.localremove", QtInfoMsg) +Q_LOGGING_CATEGORY(lcPropagateLocalMkdir, "sync.propagator.localmkdir", QtInfoMsg) +Q_LOGGING_CATEGORY(lcPropagateLocalRename, "sync.propagator.localrename", QtInfoMsg) + /** * Code inspired from Qt5's QDir::removeRecursively * The code will update the database in case of error. @@ -71,7 +74,7 @@ bool PropagateLocalRemove::removeRecursively(const QString& path) if (!ok) { _error += PropagateLocalRemove::tr("Error removing '%1': %2;"). arg(QDir::toNativeSeparators(di.filePath()), removeError) + " "; - qDebug() << "Error removing " << di.filePath() << ':' << removeError; + qCDebug(lcPropagateLocalRemove) << "Error removing " << di.filePath() << ':' << removeError; } } if (success && !ok) { @@ -97,7 +100,7 @@ bool PropagateLocalRemove::removeRecursively(const QString& path) if (!success) { _error += PropagateLocalRemove::tr("Could not remove folder '%1'") .arg(QDir::toNativeSeparators(absolute)) + " "; - qDebug() << "Error removing folder" << absolute; + qCDebug(lcPropagateLocalRemove) << "Error removing folder" << absolute; } } return success; @@ -110,7 +113,7 @@ void PropagateLocalRemove::start() QString filename = propagator()->_localDir + _item->_file; - qDebug() << filename; + qCDebug(lcPropagateLocalRemove) << filename; if( propagator()->localFileNameClash(_item->_file)) { done(SyncFileItem::NormalError, tr("Could not remove %1 because of a local file name clash") @@ -159,7 +162,7 @@ void PropagateLocalMkdir::start() } if( Utility::fsCasePreserving() && propagator()->localFileNameClash(_item->_file ) ) { - qDebug() << "WARN: new folder to create locally already exists!"; + qCDebug(lcPropagateLocalMkdir) << "WARN: new folder to create locally already exists!"; done( SyncFileItem::NormalError, tr("Attention, possible case sensitivity clash with %1").arg(newDirStr) ); return; } @@ -203,7 +206,7 @@ void PropagateLocalRename::start() // to _item->renameTarget and the file is not moved as a result. if (_item->_file != _item->_renameTarget) { propagator()->reportProgress(*_item, 0); - qDebug() << "MOVE " << existingFile << " => " << targetFile; + qCDebug(lcPropagateLocalRename) << "MOVE " << existingFile << " => " << targetFile; if (QString::compare(_item->_file, _item->_renameTarget, Qt::CaseInsensitive) != 0 && propagator()->localFileNameClash(_item->_renameTarget)) { diff --git a/src/libsync/propagatorjobs.h b/src/libsync/propagatorjobs.h index 88413d34e..2a30b3cec 100644 --- a/src/libsync/propagatorjobs.h +++ b/src/libsync/propagatorjobs.h @@ -17,7 +17,6 @@ #include "owncloudpropagator.h" #include -#include namespace OCC { diff --git a/src/libsync/syncengine.cpp b/src/libsync/syncengine.cpp index 940ae4f8f..9c6935ec0 100644 --- a/src/libsync/syncengine.cpp +++ b/src/libsync/syncengine.cpp @@ -36,9 +36,9 @@ #include #include -#include #include #include +#include #include #include #include @@ -54,6 +54,8 @@ extern "C" const char *csync_instruction_str(enum csync_instructions_e instr); namespace OCC { +Q_LOGGING_CATEGORY(lcEngine, "sync.engine") + bool SyncEngine::s_anySyncRunning = false; qint64 SyncEngine::minimumFileAgeForUpload = 2000; @@ -215,7 +217,7 @@ QString SyncEngine::csyncErrorToString(CSYNC_STATUS err) bool SyncEngine::checkErrorBlacklisting( SyncFileItem &item ) { if( !_journal ) { - qWarning() << "Journal is undefined!"; + qCWarning(lcEngine) << "Journal is undefined!"; return false; } @@ -231,7 +233,7 @@ bool SyncEngine::checkErrorBlacklisting( SyncFileItem &item ) // If duration has expired, it's not blacklisted anymore time_t now = Utility::qDateTimeToTime_t(QDateTime::currentDateTime()); if( now >= entry._lastTryTime + entry._ignoreDuration ) { - qDebug() << "blacklist entry for " << item._file << " has expired!"; + qCDebug(lcEngine) << "blacklist entry for " << item._file << " has expired!"; return false; } @@ -241,24 +243,24 @@ bool SyncEngine::checkErrorBlacklisting( SyncFileItem &item ) if(item._modtime == 0 || entry._lastTryModtime == 0) { return false; } else if( item._modtime != entry._lastTryModtime ) { - qDebug() << item._file << " is blacklisted, but has changed mtime!"; + qCDebug(lcEngine) << item._file << " is blacklisted, but has changed mtime!"; return false; } else if( item._renameTarget != entry._renameTarget) { - qDebug() << item._file << " is blacklisted, but rename target changed from" << entry._renameTarget; + qCDebug(lcEngine) << item._file << " is blacklisted, but rename target changed from" << entry._renameTarget; return false; } } else if( item._direction == SyncFileItem::Down ) { // download, check the etag. if( item._etag.isEmpty() || entry._lastTryEtag.isEmpty() ) { - qDebug() << item._file << "one ETag is empty, no blacklisting"; + qCDebug(lcEngine) << item._file << "one ETag is empty, no blacklisting"; return false; } else if( item._etag != entry._lastTryEtag ) { - qDebug() << item._file << " is blacklisted, but has changed etag!"; + qCDebug(lcEngine) << item._file << " is blacklisted, but has changed etag!"; return false; } } - qDebug() << "Item is on blacklist: " << entry._file + qCDebug(lcEngine) << "Item is on blacklist: " << entry._file << "retries:" << entry._retryCount << "for another" << (entry._lastTryTime + entry._ignoreDuration - now) << "s"; item._instruction = CSYNC_INSTRUCTION_ERROR; @@ -285,7 +287,7 @@ void SyncEngine::deleteStaleDownloadInfos(const SyncFileItemVector &syncItems) _journal->getAndDeleteStaleDownloadInfos(download_file_paths); foreach (const SyncJournalDb::DownloadInfo & deleted_info, deleted_infos) { const QString tmppath = _propagator->getFilePath(deleted_info._tmpfile); - qDebug() << "Deleting stale temporary file: " << tmppath; + qCDebug(lcEngine) << "Deleting stale temporary file: " << tmppath; FileSystem::remove(tmppath); } } @@ -361,12 +363,12 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) auto instruction = file->instruction; if (utf8State.invalidChars > 0 || utf8State.remainingChars > 0) { - qWarning() << "File ignored because of invalid utf-8 sequence: " << file->path; + qCWarning(lcEngine) << "File ignored because of invalid utf-8 sequence: " << file->path; instruction = CSYNC_INSTRUCTION_IGNORE; } else { renameTarget = codec->toUnicode(file->rename_path, qstrlen(file->rename_path), &utf8State); if (utf8State.invalidChars > 0 || utf8State.remainingChars > 0) { - qWarning() << "File ignored because of invalid utf-8 sequence in the rename_path: " << file->path << file->rename_path; + qCWarning(lcEngine) << "File ignored because of invalid utf-8 sequence in the rename_path: " << file->path << file->rename_path; instruction = CSYNC_INSTRUCTION_IGNORE; } if (instruction == CSYNC_INSTRUCTION_RENAME) { @@ -390,7 +392,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) item->_modtime = file->modtime; } else { if (instruction != CSYNC_INSTRUCTION_NONE) { - qWarning() << "ERROR: Instruction" << item->_instruction << "vs" << instruction << "for" << fileUtf8; + qCWarning(lcEngine) << "ERROR: Instruction" << item->_instruction << "vs" << instruction << "for" << fileUtf8; ASSERT(false); // Set instruction to NONE for safety. file->instruction = item->_instruction = instruction = CSYNC_INSTRUCTION_NONE; @@ -629,7 +631,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) // issues or DST changes. (We simply ignore files that goes in the past less than // two hours for the backup detection heuristics.) _backInTimeFiles++; - qDebug() << file->path << "has a timestamp earlier than the local file"; + qCDebug(lcEngine) << file->path << "has a timestamp earlier than the local file"; } else if (difftime > 0) { _hasForwardInTimeFiles = true; } @@ -687,10 +689,10 @@ void SyncEngine::handleSyncError(CSYNC *ctx, const char *state) { if( errStr.contains("ownclouds://") ) errStr.replace("ownclouds://", "https://"); if( errStr.contains("owncloud://") ) errStr.replace("owncloud://", "http://"); - qDebug() << " #### ERROR during "<< state << ": " << errStr; + qCDebug(lcEngine) << " #### ERROR during "<< state << ": " << errStr; if( CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_ABORTED) ) { - qDebug() << "Update phase was aborted by user!"; + qCDebug(lcEngine) << "Update phase was aborted by user!"; } else if( CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_SERVICE_UNAVAILABLE ) || CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_CONNECT_ERROR )) { emit csyncUnavailable(); @@ -705,7 +707,7 @@ void SyncEngine::startSync() if (_journal->exists()) { QVector< SyncJournalDb::PollInfo > pollInfos = _journal->getPollInfos(); if (!pollInfos.isEmpty()) { - qDebug() << "Finish Poll jobs before starting a sync"; + qCDebug(lcEngine) << "Finish Poll jobs before starting a sync"; CleanupPollsJob *job = new CleanupPollsJob(pollInfos, _account, _journal, _localPath, this); connect(job, SIGNAL(finished()), this, SLOT(startSync())); @@ -739,7 +741,7 @@ void SyncEngine::startSync() const qint64 minFree = criticalFreeSpaceLimit(); const qint64 freeBytes = Utility::freeDiskSpace(_localPath); if (freeBytes >= 0) { - qDebug() << "There are" << freeBytes << "bytes available at" << _localPath + qCDebug(lcEngine) << "There are" << freeBytes << "bytes available at" << _localPath << "and at least" << minFree << "are required"; if (freeBytes < minFree) { _anotherSyncNeeded = DelayedFollowUp; @@ -751,7 +753,7 @@ void SyncEngine::startSync() return; } } else { - qDebug() << "Could not determine free space available at" << _localPath; + qCDebug(lcEngine) << "Could not determine free space available at" << _localPath; } _syncItemMap.clear(); @@ -761,24 +763,24 @@ void SyncEngine::startSync() int fileRecordCount = -1; if (!_journal->exists()) { - qDebug() << "===== new sync (no sync journal exists)"; + qCDebug(lcEngine) << "New sync (no sync journal exists)"; } else { - qDebug() << "===== sync with existing sync journal"; + qCDebug(lcEngine) << "Sync with existing sync journal"; } - QString verStr("===== Using Qt "); + QString verStr("Using Qt "); verStr.append( qVersion() ); #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) verStr.append( " SSL library " ).append(QSslSocket::sslLibraryVersionString().toUtf8().data()); #endif verStr.append( " on ").append(Utility::platformName()); - qDebug() << verStr; + qCDebug(lcEngine) << verStr; fileRecordCount = _journal->getFileRecordCount(); // this creates the DB if it does not exist yet if( fileRecordCount == -1 ) { - qDebug() << "No way to create a sync journal!"; + qCDebug(lcEngine) << "No way to create a sync journal!"; emit csyncError(tr("Unable to open or create the local sync database. Make sure you have write access in the sync folder.")); finalize(false); return; @@ -795,9 +797,9 @@ void SyncEngine::startSync() auto selectiveSyncBlackList = _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok); if (ok) { bool usingSelectiveSync = (!selectiveSyncBlackList.isEmpty()); - qDebug() << Q_FUNC_INFO << (usingSelectiveSync ? "====Using Selective Sync" : "====NOT Using Selective Sync"); + qCDebug(lcEngine) << (usingSelectiveSync ? "Using Selective Sync" : "NOT Using Selective Sync"); } else { - qDebug() << Q_FUNC_INFO << "Could not retrieve selective sync list from DB"; + qCDebug(lcEngine) << "Could not retrieve selective sync list from DB"; emit csyncError(tr("Unable to read the blacklist from the local database")); finalize(false); return; @@ -810,7 +812,7 @@ void SyncEngine::startSync() _stopWatch.start(); - qDebug() << "#### Discovery start #################################################### >>"; + qCDebug(lcEngine) << "#### Discovery start #################################################### >>"; // Usually the discovery runs in the background: We want to avoid // stealing too much time from other processes that the user might @@ -820,7 +822,7 @@ void SyncEngine::startSync() _discoveryMainThread = new DiscoveryMainThread(account()); _discoveryMainThread->setParent(this); connect(this, SIGNAL(finished(bool)), _discoveryMainThread, SLOT(deleteLater())); - qDebug() << "=====Server" << account()->serverVersion() + qCDebug(lcEngine) << "=====Server" << account()->serverVersion() << QString("rootEtagChangesNotOnlySubFolderEtags=%1").arg(account()->rootEtagChangesNotOnlySubFolderEtags()); if (account()->rootEtagChangesNotOnlySubFolderEtags()) { connect(_discoveryMainThread, SIGNAL(etag(QString)), this, SLOT(slotRootEtagReceived(QString))); @@ -834,7 +836,7 @@ void SyncEngine::startSync() _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok); if (!ok) { delete discoveryJob; - qDebug() << Q_FUNC_INFO << "Unable to read selective sync list, aborting."; + qCDebug(lcEngine) << "Unable to read selective sync list, aborting."; emit csyncError(tr("Unable to read from the sync journal.")); finalize(false); return; @@ -860,7 +862,7 @@ void SyncEngine::startSync() void SyncEngine::slotRootEtagReceived(const QString &e) { if (_remoteRootEtag.isEmpty()) { - qDebug() << Q_FUNC_INFO << e; + qCDebug(lcEngine) << e; _remoteRootEtag = e; emit rootEtag(_remoteRootEtag); } @@ -875,11 +877,11 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) handleSyncError(_csync_ctx, "csync_update"); return; } - qDebug() << "<<#### Discovery end #################################################### " << _stopWatch.addLapTime(QLatin1String("Discovery Finished")); + qCDebug(lcEngine) << "<<#### Discovery end #################################################### " << _stopWatch.addLapTime(QLatin1String("Discovery Finished")); // Sanity check if (!_journal->isConnected()) { - qDebug() << "Bailing out, DB failure"; + qCDebug(lcEngine) << "Bailing out, DB failure"; emit csyncError(tr("Cannot open the sync journal")); finalize(false); return; @@ -893,7 +895,7 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) return; } - qDebug() << "<<#### Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Reconcile Finished")); + qCDebug(lcEngine) << "<<#### Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Reconcile Finished")); _hasNoneFiles = false; _hasRemoveFile = false; @@ -907,16 +909,16 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) _renamedFolders.clear(); if( csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0 ) { - qDebug() << "Error in local treewalk."; + qCDebug(lcEngine) << "Error in local treewalk."; walkOk = false; } if( walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0 ) { - qDebug() << "Error in remote treewalk."; + qCDebug(lcEngine) << "Error in remote treewalk."; } if (_csync_ctx->remote.root_perms) { _remotePerms[QLatin1String("")] = _csync_ctx->remote.root_perms; - qDebug() << "Permissions of the root folder: " << _remotePerms[QLatin1String("")]; + qCDebug(lcEngine) << "Permissions of the root folder: " << _remotePerms[QLatin1String("")]; } // Re-init the csync context to free memory @@ -946,11 +948,11 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) } if (!_hasNoneFiles && _hasRemoveFile) { - qDebug() << Q_FUNC_INFO << "All the files are going to be changed, asking the user"; + qCDebug(lcEngine) << "All the files are going to be changed, asking the user"; bool cancel = false; emit aboutToRemoveAllFiles(syncItems.first()->_direction, &cancel); if (cancel) { - qDebug() << Q_FUNC_INFO << "Abort sync"; + qCDebug(lcEngine) << "Abort sync"; finalize(false); return; } @@ -962,14 +964,14 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) // Note that an empty ("") fingerprint is valid and means it was empty on the server before. if (!databaseFingerprint.isNull() && _discoveryMainThread->_dataFingerprint != databaseFingerprint) { - qDebug() << "data fingerprint changed, assume restore from backup" << databaseFingerprint << _discoveryMainThread->_dataFingerprint; + qCDebug(lcEngine) << "data fingerprint changed, assume restore from backup" << databaseFingerprint << _discoveryMainThread->_dataFingerprint; restoreOldFiles(syncItems); } else if (!_hasForwardInTimeFiles && _backInTimeFiles >= 2 && _account->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) { // The server before ownCloud 9.1 did not have the data-fingerprint property. So in that // case we use heuristics to detect restored backup. This is disabled with newer version // because this causes troubles to the user and is not as reliable as the data-fingerprint. - qDebug() << "All the changes are bringing files in the past, asking the user"; + qCDebug(lcEngine) << "All the changes are bringing files in the past, asking the user"; // this typically happen when a backup is restored on the server bool restore = false; emit aboutToRestoreBackup(&restore); @@ -995,10 +997,10 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) #ifndef NDEBUG QString script = qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT"); - qDebug() << "OOO => Post Update Script: " << script; + qCDebug(lcEngine) << "OOO => Post Update Script: " << script; QProcess::execute(script.toUtf8()); #else - qWarning() << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG"; + qCWarning(lcEngine) << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG"; #endif } @@ -1030,7 +1032,7 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) _propagator->start(syncItems); - qDebug() << "<<#### Post-Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Post-Reconcile Finished")); + qCDebug(lcEngine) << "<<#### Post-Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Post-Reconcile Finished")); } void SyncEngine::slotCleanPollsJobAborted(const QString &error) @@ -1061,14 +1063,14 @@ void SyncEngine::setNetworkLimits(int upload, int download) ; if( propDownloadLimit != 0 || propUploadLimit != 0 ) { - qDebug() << " N------N Network Limits (down/up) " << propDownloadLimit << propUploadLimit; + qCDebug(lcEngine) << " N------N Network Limits (down/up) " << propDownloadLimit << propUploadLimit; } } void SyncEngine::slotItemCompleted(const SyncFileItemPtr &item) { const char * instruction_str = csync_instruction_str(item->_instruction); - qDebug() << Q_FUNC_INFO << item->_file << instruction_str << item->_status << item->_errorString; + qCDebug(lcEngine) << item->_file << instruction_str << item->_status << item->_errorString; _progressInfo->setProgressComplete(*item); @@ -1092,7 +1094,7 @@ void SyncEngine::slotFinished(bool success) // emit the treewalk results. if( ! _journal->postSyncCleanup( _seenFiles, _temporarilyUnavailablePaths ) ) { - qDebug() << "Cleaning of synced "; + qCDebug(lcEngine) << "Cleaning of synced "; } _journal->commit("All Finished.", false); @@ -1114,7 +1116,7 @@ void SyncEngine::finalize(bool success) csync_commit(_csync_ctx); _journal->close(); - qDebug() << "CSync run took " << _stopWatch.addLapTime(QLatin1String("Sync Finished")); + qCDebug(lcEngine) << "CSync run took " << _stopWatch.addLapTime(QLatin1String("Sync Finished")); _stopWatch.stop(); s_anySyncRunning = false; @@ -1199,7 +1201,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) // No permissions set break; } else if ((*it)->_isDirectory && !perms.contains("K")) { - qDebug() << "checkForPermission: ERROR" << (*it)->_file; + qCDebug(lcEngine) << "checkForPermission: ERROR" << (*it)->_file; (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; (*it)->_status = SyncFileItem::NormalError; (*it)->_errorString = tr("Not allowed because you don't have permission to add subfolders to that folder"); @@ -1213,7 +1215,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) // but delete and upload. It will then be restored if needed. _journal->avoidRenamesOnNextSync((*it)->_file); _anotherSyncNeeded = ImmediateFollowUp; - qDebug() << "Moving of " << (*it)->_file << " canceled because no permission to add parent folder"; + qCDebug(lcEngine) << "Moving of " << (*it)->_file << " canceled because no permission to add parent folder"; } (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; (*it)->_status = SyncFileItem::SoftError; @@ -1221,7 +1223,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) } } else if (!(*it)->_isDirectory && !perms.contains("C")) { - qDebug() << "checkForPermission: ERROR" << (*it)->_file; + qCDebug(lcEngine) << "checkForPermission: ERROR" << (*it)->_file; (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; (*it)->_status = SyncFileItem::NormalError; (*it)->_errorString = tr("Not allowed because you don't have permission to add files in that folder"); @@ -1234,7 +1236,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) // No permissions set break; } if (!perms.contains("W")) { - qDebug() << "checkForPermission: RESTORING" << (*it)->_file; + qCDebug(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; (*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT; (*it)->_direction = SyncFileItem::Down; (*it)->_isRestoration = true; @@ -1255,7 +1257,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) break; } if (!perms.contains("D")) { - qDebug() << "checkForPermission: RESTORING" << (*it)->_file; + qCDebug(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; (*it)->_instruction = CSYNC_INSTRUCTION_NEW; (*it)->_direction = SyncFileItem::Down; (*it)->_isRestoration = true; @@ -1268,12 +1270,12 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) it = it_next; if ((*it)->_instruction != CSYNC_INSTRUCTION_REMOVE) { - qWarning() << "non-removed job within a removed folder" + qCWarning(lcEngine) << "non-removed job within a removed folder" << (*it)->_file << (*it)->_instruction; continue; } - qDebug() << "checkForPermission: RESTORING" << (*it)->_file; + qCDebug(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; (*it)->_instruction = CSYNC_INSTRUCTION_NEW; (*it)->_direction = SyncFileItem::Down; @@ -1349,7 +1351,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) (*it)->_direction = SyncFileItem::Down; (*it)->_errorString = tr("Move not allowed, item restored"); (*it)->_isRestoration = true; - qDebug() << "checkForPermission: MOVING BACK" << (*it)->_file; + qCDebug(lcEngine) << "checkForPermission: MOVING BACK" << (*it)->_file; // in case something does wrong, we will not do it next time _journal->avoidRenamesOnNextSync((*it)->_file); } else @@ -1362,7 +1364,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) sourceOK ? tr("the destination") : tr("the source")); (*it)->_errorString = errorString; - qDebug() << "checkForPermission: ERROR MOVING" << (*it)->_file << errorString; + qCDebug(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file << errorString; // Avoid a rename on next sync: // TODO: do the resolution now already so we don't need two sync @@ -1379,7 +1381,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; (*it)->_status = SyncFileItem::NormalError; (*it)->_errorString = errorString; - qDebug() << "checkForPermission: ERROR MOVING" << (*it)->_file; + qCDebug(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file; } } } @@ -1417,11 +1419,11 @@ void SyncEngine::restoreOldFiles(SyncFileItemVector &syncItems) switch ((*it)->_instruction) { case CSYNC_INSTRUCTION_SYNC: - qDebug() << "restoreOldFiles: RESTORING" << (*it)->_file; + qCDebug(lcEngine) << "restoreOldFiles: RESTORING" << (*it)->_file; (*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT; break; case CSYNC_INSTRUCTION_REMOVE: - qDebug() << "restoreOldFiles: RESTORING" << (*it)->_file; + qCDebug(lcEngine) << "restoreOldFiles: RESTORING" << (*it)->_file; (*it)->_instruction = CSYNC_INSTRUCTION_NEW; (*it)->_direction = SyncFileItem::Up; break; @@ -1469,7 +1471,7 @@ void SyncEngine::abort() { // Sets a flag for the update phase csync_request_abort(_csync_ctx); - qDebug() << Q_FUNC_INFO << _discoveryMainThread; + qCDebug(lcEngine) << "Aborting sync, _discoveryMainThread:" << _discoveryMainThread; // Aborts the discovery phase job if (_discoveryMainThread) { _discoveryMainThread->abort(); diff --git a/src/libsync/syncfilestatus.cpp b/src/libsync/syncfilestatus.cpp index 5eec5c188..722a60785 100644 --- a/src/libsync/syncfilestatus.cpp +++ b/src/libsync/syncfilestatus.cpp @@ -14,8 +14,6 @@ #include "syncfilestatus.h" -#include - namespace OCC { SyncFileStatus::SyncFileStatus() :_tag(StatusNone), _sharedWithMe(false) diff --git a/src/libsync/syncfilestatustracker.cpp b/src/libsync/syncfilestatustracker.cpp index df54c8cdf..a3f5030b8 100644 --- a/src/libsync/syncfilestatustracker.cpp +++ b/src/libsync/syncfilestatustracker.cpp @@ -19,15 +19,19 @@ #include "syncjournalfilerecord.h" #include "asserts.h" +#include + namespace OCC { +Q_LOGGING_CATEGORY(lcStatusTracker, "sync.statustracker", QtInfoMsg) + static SyncFileStatus::SyncFileStatusTag lookupProblem(const QString &pathToMatch, const std::map &problemMap) { auto lower = problemMap.lower_bound(pathToMatch); for (auto it = lower; it != problemMap.cend(); ++it) { const QString &problemPath = it->first; SyncFileStatus::SyncFileStatusTag severity = it->second; - // qDebug() << Q_FUNC_INFO << pathToMatch << severity << problemPath; + if (problemPath == pathToMatch) { return severity; } else if (severity == SyncFileStatus::StatusError @@ -181,7 +185,7 @@ void SyncFileStatusTracker::slotAboutToPropagate(SyncFileItemVector& items) std::swap(_syncProblems, oldProblems); foreach (const SyncFileItemPtr &item, items) { - // qDebug() << Q_FUNC_INFO << "Investigating" << item->destination() << item->_status << item->_instruction; + qCDebug(lcStatusTracker) << "Investigating" << item->destination() << item->_status << item->_instruction; _dirtyPaths.remove(item->destination()); if (showErrorInSocketApi(*item)) { @@ -226,7 +230,7 @@ void SyncFileStatusTracker::slotAboutToPropagate(SyncFileItemVector& items) void SyncFileStatusTracker::slotItemCompleted(const SyncFileItemPtr &item) { - // qDebug() << Q_FUNC_INFO << item.destination() << item._status << item._instruction; + qCDebug(lcStatusTracker) << "Item completed" << item->destination() << item->_status << item->_instruction; if (showErrorInSocketApi(*item)) { _syncProblems[item->_file] = SyncFileStatus::StatusError; diff --git a/src/libsync/syncjournaldb.cpp b/src/libsync/syncjournaldb.cpp index 43ef9b37a..5fc201c89 100644 --- a/src/libsync/syncjournaldb.cpp +++ b/src/libsync/syncjournaldb.cpp @@ -13,8 +13,8 @@ */ #include +#include #include -#include #include #include @@ -33,6 +33,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcDb, "sync.database", QtInfoMsg) + SyncJournalDb::SyncJournalDb(const QString& dbFilePath, QObject *parent) : QObject(parent), _dbFile(dbFilePath), @@ -80,43 +82,43 @@ bool SyncJournalDb::maybeMigrateDb(const QString& localPath, const QString& abso if( FileSystem::fileExists( newDbName ) ) { if( !FileSystem::remove(newDbName, &error) ) { - qDebug() << "Database migration: Could not remove db file" << newDbName + qCDebug(lcDb) << "Database migration: Could not remove db file" << newDbName << "due to" << error; return false; } } if( FileSystem::fileExists( newDbNameWal ) ) { if( !FileSystem::remove(newDbNameWal, &error) ) { - qDebug() << "Database migration: Could not remove db WAL file" << newDbNameWal + qCDebug(lcDb) << "Database migration: Could not remove db WAL file" << newDbNameWal << "due to" << error; return false; } } if( FileSystem::fileExists( newDbNameShm ) ) { if( !FileSystem::remove(newDbNameShm, &error) ) { - qDebug() << "Database migration: Could not remove db SHM file" << newDbNameShm + qCDebug(lcDb) << "Database migration: Could not remove db SHM file" << newDbNameShm << "due to" << error; return false; } } if( !FileSystem::rename(oldDbName, newDbName, &error) ) { - qDebug() << "Database migration: could not rename " << oldDbName + qCDebug(lcDb) << "Database migration: could not rename " << oldDbName << "to" << newDbName << ":" << error; return false; } if( !FileSystem::rename(oldDbNameWal, newDbNameWal, &error) ) { - qDebug() << "Database migration: could not rename " << oldDbNameWal + qCDebug(lcDb) << "Database migration: could not rename " << oldDbNameWal << "to" << newDbNameWal << ":" << error; return false; } if( !FileSystem::rename(oldDbNameShm, newDbNameShm, &error) ) { - qDebug() << "Database migration: could not rename " << oldDbNameShm + qCDebug(lcDb) << "Database migration: could not rename " << oldDbNameShm << "to" << newDbNameShm << ":" << error; return false; } - qDebug() << "Journal successfully migrated from" << oldDbName << "to" << newDbName; + qCDebug(lcDb) << "Journal successfully migrated from" << oldDbName << "to" << newDbName; return true; } @@ -141,9 +143,9 @@ void SyncJournalDb::walCheckpoint() SqlQuery pragma1(_db); pragma1.prepare("PRAGMA wal_checkpoint(FULL);"); if (!pragma1.exec()) { - qDebug() << pragma1.error(); + qCDebug(lcDb) << pragma1.error(); } else { - qDebug() << Q_FUNC_INFO << "took" << t.elapsed() << "msec"; + qCDebug(lcDb) << "took" << t.elapsed() << "msec"; } } @@ -151,13 +153,13 @@ void SyncJournalDb::startTransaction() { if( _transaction == 0 ) { if( !_db.transaction() ) { - qDebug() << "ERROR starting transaction: " << _db.error(); + qCDebug(lcDb) << "ERROR starting transaction: " << _db.error(); return; } _transaction = 1; - // qDebug() << "XXX Transaction start!"; + // qCDebug(lcDb) << "XXX Transaction start!"; } else { - qDebug() << "Database Transaction is running, not starting another one!"; + qCDebug(lcDb) << "Database Transaction is running, not starting another one!"; } } @@ -165,20 +167,20 @@ void SyncJournalDb::commitTransaction() { if( _transaction == 1 ) { if( ! _db.commit() ) { - qDebug() << "ERROR committing to the database: " << _db.error(); + qCDebug(lcDb) << "ERROR committing to the database: " << _db.error(); return; } _transaction = 0; - // qDebug() << "XXX Transaction END!"; + // qCDebug(lcDb) << "XXX Transaction END!"; } else { - qDebug() << "No database Transaction to commit"; + qCDebug(lcDb) << "No database Transaction to commit"; } } bool SyncJournalDb::sqlFail( const QString& log, const SqlQuery& query ) { commitTransaction(); - qWarning() << "SQL Error" << log << query.error(); + qCWarning(lcDb) << "SQL Error" << log << query.error(); ASSERT(false); _db.close(); return false; @@ -190,9 +192,9 @@ static QString defaultJournalMode(const QString & dbPath) // See #2693: Some exFAT file systems seem unable to cope with the // WAL journaling mode. They work fine with DELETE. QString fileSystem = FileSystem::fileSystemForPath(dbPath); - qDebug() << "Detected filesystem" << fileSystem << "for" << dbPath; + qCDebug(lcDb) << "Detected filesystem" << fileSystem << "for" << dbPath; if (fileSystem.contains("FAT")) { - qDebug() << "Filesystem contains FAT - using DELETE journal mode"; + qCDebug(lcDb) << "Filesystem contains FAT - using DELETE journal mode"; return "DELETE"; } #else @@ -208,19 +210,19 @@ bool SyncJournalDb::checkConnect() } if( _dbFile.isEmpty()) { - qDebug() << "Database filename" + _dbFile + " is empty"; + qCDebug(lcDb) << "Database filename" + _dbFile + " is empty"; return false; } // The database file is created by this call (SQLITE_OPEN_CREATE) if( !_db.openOrCreateReadWrite(_dbFile) ) { QString error = _db.error(); - qDebug() << "Error opening the db: " << error; + qCDebug(lcDb) << "Error opening the db: " << error; return false; } if( !QFile::exists(_dbFile) ) { - qDebug() << "Database file" + _dbFile + " does not exist"; + qCDebug(lcDb) << "Database file" + _dbFile + " does not exist"; return false; } @@ -230,7 +232,7 @@ bool SyncJournalDb::checkConnect() return sqlFail("SELECT sqlite_version()", pragma1); } else { pragma1.next(); - qDebug() << "sqlite3 version" << pragma1.stringValue(0); + qCDebug(lcDb) << "sqlite3 version" << pragma1.stringValue(0); } // Allow forcing the journal mode for debugging @@ -244,7 +246,7 @@ bool SyncJournalDb::checkConnect() return sqlFail("Set PRAGMA journal_mode", pragma1); } else { pragma1.next(); - qDebug() << "sqlite3 journal_mode=" << pragma1.stringValue(0); + qCDebug(lcDb) << "sqlite3 journal_mode=" << pragma1.stringValue(0); } // For debugging purposes, allow temp_store to be set @@ -254,7 +256,7 @@ bool SyncJournalDb::checkConnect() if (!pragma1.exec()) { return sqlFail("Set PRAGMA temp_store", pragma1); } - qDebug() << "sqlite3 with temp_store =" << env_temp_store; + qCDebug(lcDb) << "sqlite3 with temp_store =" << env_temp_store; } pragma1.prepare("PRAGMA synchronous = 1;"); @@ -385,7 +387,7 @@ bool SyncJournalDb::checkConnect() SqlQuery versionQuery("SELECT major, minor, patch FROM version;", _db); if (!versionQuery.next()) { // If there was no entry in the table, it means we are likely upgrading from 1.5 - qDebug() << Q_FUNC_INFO << "possibleUpgradeFromMirall_1_5 detected!"; + qCDebug(lcDb) << "possibleUpgradeFromMirall_1_5 detected!"; forceRemoteDiscovery = true; createQuery.prepare("INSERT INTO version VALUES (?1, ?2, ?3, ?4);"); @@ -403,7 +405,7 @@ bool SyncJournalDb::checkConnect() int patch = versionQuery.intValue(2); if( major == 1 && minor == 8 && (patch == 0 || patch == 1) ) { - qDebug() << Q_FUNC_INFO << "possibleUpgradeFromMirall_1_8_0_or_1 detected!"; + qCDebug(lcDb) << "possibleUpgradeFromMirall_1_8_0_or_1 detected!"; forceRemoteDiscovery = true; } @@ -411,7 +413,7 @@ bool SyncJournalDb::checkConnect() // local files and a remote discovery will fix them. // See #5190 #5242. if( major == 2 && minor < 3) { - qDebug() << Q_FUNC_INFO << "upgrade form client < 2.3.0 detected! forcing remote discovery"; + qCDebug(lcDb) << "upgrade form client < 2.3.0 detected! forcing remote discovery"; forceRemoteDiscovery = true; } @@ -437,7 +439,7 @@ bool SyncJournalDb::checkConnect() bool rc = updateDatabaseStructure(); if( !rc ) { - qDebug() << "WARN: Failed to update the database structure!"; + qCDebug(lcDb) << "WARN: Failed to update the database structure!"; } /* @@ -600,7 +602,7 @@ bool SyncJournalDb::checkConnect() void SyncJournalDb::close() { QMutexLocker locker(&_mutex); - qDebug() << Q_FUNC_INFO << _dbFile; + qCDebug(lcDb) << "Closing DB" << _dbFile; commitTransaction(); @@ -797,7 +799,7 @@ QStringList SyncJournalDb::tableColumns( const QString& table ) if(!query.exec()) { QString err = query.error(); - qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;; + qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;; return columns; } @@ -806,7 +808,7 @@ QStringList SyncJournalDb::tableColumns( const QString& table ) } } } - qDebug() << "Columns in the current journal: " << columns; + qCDebug(lcDb) << "Columns in the current journal: " << columns; return columns; } @@ -836,7 +838,7 @@ bool SyncJournalDb::setFileRecord( const SyncJournalFileRecord& _record ) QString prefix = record._path + "/"; foreach(const QString &it, _avoidReadFromDbOnNextSyncFilter) { if (it.startsWith(prefix)) { - qDebug() << "Filtered writing the etag of" << prefix << "because it is a prefix of" << it; + qCDebug(lcDb) << "Filtered writing the etag of" << prefix << "because it is a prefix of" << it; record._etag = "_invalid_"; break; } @@ -874,12 +876,12 @@ bool SyncJournalDb::setFileRecord( const SyncJournalFileRecord& _record ) _setFileRecordQuery->bindValue(16, contentChecksumTypeId ); if( !_setFileRecordQuery->exec() ) { - qWarning() << "Error SQL statement setFileRecord: " << _setFileRecordQuery->lastQuery() << " :" + qCWarning(lcDb) << "Error SQL statement setFileRecord: " << _setFileRecordQuery->lastQuery() << " :" << _setFileRecordQuery->error(); return false; } - qDebug() << _setFileRecordQuery->lastQuery() << phash << plen << record._path << record._inode + qCDebug(lcDb) << _setFileRecordQuery->lastQuery() << phash << plen << record._path << record._inode << QString::number(Utility::qDateTimeToTime_t(record._modtime)) << QString::number(record._type) << record._etag << record._fileId << record._remotePerm << record._fileSize << (record._serverHasIgnoredFiles ? 1:0) << record._contentChecksum << record._contentChecksumType << contentChecksumTypeId; @@ -887,7 +889,7 @@ bool SyncJournalDb::setFileRecord( const SyncJournalFileRecord& _record ) _setFileRecordQuery->reset_and_clear_bindings(); return true; } else { - qDebug() << "Failed to connect database."; + qCDebug(lcDb) << "Failed to connect database."; return false; // checkConnect failed. } } @@ -905,28 +907,28 @@ bool SyncJournalDb::deleteFileRecord(const QString& filename, bool recursively) _deleteFileRecordPhash->bindValue( 1, QString::number(phash) ); if( !_deleteFileRecordPhash->exec() ) { - qWarning() << "Exec error of SQL statement: " + qCWarning(lcDb) << "Exec error of SQL statement: " << _deleteFileRecordPhash->lastQuery() << " : " << _deleteFileRecordPhash->error(); return false; } - qDebug() << _deleteFileRecordPhash->lastQuery() << phash << filename; + qCDebug(lcDb) << _deleteFileRecordPhash->lastQuery() << phash << filename; _deleteFileRecordPhash->reset_and_clear_bindings(); if( recursively) { _deleteFileRecordRecursively->reset_and_clear_bindings(); _deleteFileRecordRecursively->bindValue(1, filename); if( !_deleteFileRecordRecursively->exec() ) { - qWarning() << "Exec error of SQL statement: " + qCWarning(lcDb) << "Exec error of SQL statement: " << _deleteFileRecordRecursively->lastQuery() << " : " << _deleteFileRecordRecursively->error(); return false; } - qDebug() << _deleteFileRecordRecursively->lastQuery() << filename; + qCDebug(lcDb) << _deleteFileRecordRecursively->lastQuery() << filename; _deleteFileRecordRecursively->reset_and_clear_bindings(); } return true; } else { - qDebug() << "Failed to connect database."; + qCDebug(lcDb) << "Failed to connect database."; return false; // checkConnect failed. } } @@ -945,7 +947,7 @@ SyncJournalFileRecord SyncJournalDb::getFileRecord(const QString& filename) if (!_getFileRecordQuery->exec()) { QString err = _getFileRecordQuery->error(); - qDebug() << "Error creating prepared statement: " << _getFileRecordQuery->lastQuery() << ", Error:" << err;; + qCDebug(lcDb) << "Error creating prepared statement: " << _getFileRecordQuery->lastQuery() << ", Error:" << err;; locker.unlock(); close(); return rec; @@ -973,7 +975,7 @@ SyncJournalFileRecord SyncJournalDb::getFileRecord(const QString& filename) int errId = _getFileRecordQuery->errorId(); if( errId != SQLITE_DONE ) { // only do this if the problem is different from SQLITE_DONE QString err = _getFileRecordQuery->error(); - qDebug() << "No journal entry found for " << filename << "Error: " << err; + qCDebug(lcDb) << "No journal entry found for " << filename << "Error: " << err; locker.unlock(); close(); locker.relock(); @@ -1000,7 +1002,7 @@ bool SyncJournalDb::postSyncCleanup(const QSet& filepathsToKeep, if (!query.exec()) { QString err = query.error(); - qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;; + qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;; return false; } @@ -1024,12 +1026,12 @@ bool SyncJournalDb::postSyncCleanup(const QSet& filepathsToKeep, if( superfluousItems.count() ) { QString sql = "DELETE FROM metadata WHERE phash in ("+ superfluousItems.join(",")+")"; - qDebug() << "Sync Journal cleanup: " << sql; + qCDebug(lcDb) << "Sync Journal cleanup: " << sql; SqlQuery delQuery(_db); delQuery.prepare(sql); if( !delQuery.exec() ) { QString err = delQuery.error(); - qDebug() << "Error removing superfluous journal entries: " << delQuery.lastQuery() << ", Error:" << err;; + qCDebug(lcDb) << "Error removing superfluous journal entries: " << delQuery.lastQuery() << ", Error:" << err;; return false; } } @@ -1053,7 +1055,7 @@ int SyncJournalDb::getFileRecordCount() if (!query.exec()) { QString err = query.error(); - qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;; + qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;; return 0; } @@ -1073,7 +1075,7 @@ bool SyncJournalDb::updateFileRecordChecksum(const QString& filename, qlonglong phash = getPHash(filename); if( !checkConnect() ) { - qDebug() << "Failed to connect database."; + qCDebug(lcDb) << "Failed to connect database."; return false; } @@ -1086,13 +1088,13 @@ bool SyncJournalDb::updateFileRecordChecksum(const QString& filename, query->bindValue(3, checksumTypeId); if( !query->exec() ) { - qWarning() << "Error SQL statement setFileRecordChecksumQuery: " + qCWarning(lcDb) << "Error SQL statement setFileRecordChecksumQuery: " << query->lastQuery() << " :" << query->error(); return false; } - qDebug() << query->lastQuery() << phash << contentChecksum + qCDebug(lcDb) << query->lastQuery() << phash << contentChecksum << contentChecksumType << checksumTypeId; query->reset_and_clear_bindings(); @@ -1107,7 +1109,7 @@ bool SyncJournalDb::updateLocalMetadata(const QString& filename, qlonglong phash = getPHash(filename); if( !checkConnect() ) { - qDebug() << "Failed to connect database."; + qCDebug(lcDb) << "Failed to connect database."; return false; } @@ -1120,13 +1122,13 @@ bool SyncJournalDb::updateLocalMetadata(const QString& filename, query->bindValue(4, size); if( !query->exec() ) { - qWarning() << "Error SQL statement updateLocalMetadata: " + qCWarning(lcDb) << "Error SQL statement updateLocalMetadata: " << query->lastQuery() << " :" << query->error(); return false; } - qDebug() << query->lastQuery() << phash << inode + qCDebug(lcDb) << query->lastQuery() << phash << inode << modtime << size; query->reset_and_clear_bindings(); @@ -1168,14 +1170,14 @@ static bool deleteBatch(SqlQuery & query, const QStringList & entries, const QSt if (entries.isEmpty()) return true; - qDebug() << "Removing stale " << qPrintable(name) << " entries: " << entries.join(", "); + qCDebug(lcDb) << "Removing stale " << qPrintable(name) << " entries: " << entries.join(", "); // FIXME: Was ported from execBatch, check if correct! foreach( const QString& entry, entries ) { query.reset_and_clear_bindings(); query.bindValue(1, entry); if (!query.exec()) { QString err = query.error(); - qDebug() << "Error removing stale " << qPrintable(name) << " entries: " + qCDebug(lcDb) << "Error removing stale " << qPrintable(name) << " entries: " << query.lastQuery() << ", Error:" << err; return false; } @@ -1197,7 +1199,7 @@ SyncJournalDb::DownloadInfo SyncJournalDb::getDownloadInfo(const QString& file) if (!_getDownloadInfoQuery->exec()) { QString err = _getDownloadInfoQuery->error(); - qDebug() << "Database error for file " << file << " : " << _getDownloadInfoQuery->lastQuery() << ", Error:" << err;; + qCDebug(lcDb) << "Database error for file " << file << " : " << _getDownloadInfoQuery->lastQuery() << ", Error:" << err;; return res; } @@ -1227,11 +1229,11 @@ void SyncJournalDb::setDownloadInfo(const QString& file, const SyncJournalDb::Do _setDownloadInfoQuery->bindValue(4, i._errorCount ); if( !_setDownloadInfoQuery->exec() ) { - qWarning() << "Exec error of SQL statement: " << _setDownloadInfoQuery->lastQuery() << " :" << _setDownloadInfoQuery->error(); + qCWarning(lcDb) << "Exec error of SQL statement: " << _setDownloadInfoQuery->lastQuery() << " :" << _setDownloadInfoQuery->error(); return; } - qDebug() << _setDownloadInfoQuery->lastQuery() << file << i._tmpfile << i._etag << i._errorCount; + qCDebug(lcDb) << _setDownloadInfoQuery->lastQuery() << file << i._tmpfile << i._etag << i._errorCount; _setDownloadInfoQuery->reset_and_clear_bindings(); } else { @@ -1239,10 +1241,10 @@ void SyncJournalDb::setDownloadInfo(const QString& file, const SyncJournalDb::Do _deleteDownloadInfoQuery->bindValue( 1, file ); if( !_deleteDownloadInfoQuery->exec() ) { - qWarning() << "Exec error of SQL statement: " << _deleteDownloadInfoQuery->lastQuery() << " : " << _deleteDownloadInfoQuery->error(); + qCWarning(lcDb) << "Exec error of SQL statement: " << _deleteDownloadInfoQuery->lastQuery() << " : " << _deleteDownloadInfoQuery->error(); return; } - qDebug() << _deleteDownloadInfoQuery->lastQuery() << file; + qCDebug(lcDb) << _deleteDownloadInfoQuery->lastQuery() << file; _deleteDownloadInfoQuery->reset_and_clear_bindings(); } } @@ -1262,7 +1264,7 @@ QVector SyncJournalDb::getAndDeleteStaleDownloadInf if (!query.exec()) { QString err = query.error(); - qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err; + qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err; return empty_result; } @@ -1316,7 +1318,7 @@ SyncJournalDb::UploadInfo SyncJournalDb::getUploadInfo(const QString& file) if (!_getUploadInfoQuery->exec()) { QString err = _getUploadInfoQuery->error(); - qDebug() << "Database error for file " << file << " : " << _getUploadInfoQuery->lastQuery() << ", Error:" << err; + qCDebug(lcDb) << "Database error for file " << file << " : " << _getUploadInfoQuery->lastQuery() << ", Error:" << err; return res; } @@ -1352,21 +1354,21 @@ void SyncJournalDb::setUploadInfo(const QString& file, const SyncJournalDb::Uplo _setUploadInfoQuery->bindValue(6, Utility::qDateTimeToTime_t(i._modtime) ); if( !_setUploadInfoQuery->exec() ) { - qWarning() << "Exec error of SQL statement: " << _setUploadInfoQuery->lastQuery() << " :" << _setUploadInfoQuery->error(); + qCWarning(lcDb) << "Exec error of SQL statement: " << _setUploadInfoQuery->lastQuery() << " :" << _setUploadInfoQuery->error(); return; } - qDebug() << _setUploadInfoQuery->lastQuery() << file << i._chunk << i._transferid << i._errorCount; + qCDebug(lcDb) << _setUploadInfoQuery->lastQuery() << file << i._chunk << i._transferid << i._errorCount; _setUploadInfoQuery->reset_and_clear_bindings(); } else { _deleteUploadInfoQuery->reset_and_clear_bindings(); _deleteUploadInfoQuery->bindValue(1, file); if( !_deleteUploadInfoQuery->exec() ) { - qWarning() << "Exec error of SQL statement: " << _deleteUploadInfoQuery->lastQuery() << " : " << _deleteUploadInfoQuery->error(); + qCWarning(lcDb) << "Exec error of SQL statement: " << _deleteUploadInfoQuery->lastQuery() << " : " << _deleteUploadInfoQuery->error(); return; } - qDebug() << _deleteUploadInfoQuery->lastQuery() << file; + qCDebug(lcDb) << _deleteUploadInfoQuery->lastQuery() << file; _deleteUploadInfoQuery->reset_and_clear_bindings(); } } @@ -1385,7 +1387,7 @@ QVector SyncJournalDb::deleteStaleUploadInfos(const QSet &keep) if (!query.exec()) { QString err = query.error(); - qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err; + qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err; return ids; } @@ -1428,7 +1430,7 @@ SyncJournalErrorBlacklistRecord SyncJournalDb::errorBlacklistEntry( const QStrin } _getErrorBlacklistQuery->reset_and_clear_bindings(); } else { - qWarning() << "Exec error blacklist: " << _getErrorBlacklistQuery->lastQuery() << " : " + qCWarning(lcDb) << "Exec error blacklist: " << _getErrorBlacklistQuery->lastQuery() << " : " << _getErrorBlacklistQuery->error(); } } @@ -1449,7 +1451,7 @@ bool SyncJournalDb::deleteStaleErrorBlacklistEntries(const QSet &keep) if (!query.exec()) { QString err = query.error(); - qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err; + qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err; return false; } @@ -1517,7 +1519,7 @@ void SyncJournalDb::wipeErrorBlacklistEntry( const QString& file ) if( ! query.exec() ) { sqlFail("Deletion of blacklist item failed.", query); } - qDebug() << query.lastQuery() << file; + qCDebug(lcDb) << query.lastQuery() << file; } } @@ -1538,9 +1540,9 @@ void SyncJournalDb::updateErrorBlacklistEntry( const SyncJournalErrorBlacklistRe _setErrorBlacklistQuery->bindValue(8, item._renameTarget); if( !_setErrorBlacklistQuery->exec() ) { QString bug = _setErrorBlacklistQuery->error(); - qDebug() << "SQL exec blacklistitem insert or replace failed: "<< bug; + qCDebug(lcDb) << "SQL exec blacklistitem insert or replace failed: "<< bug; } - qDebug() << "set blacklist entry for " << item._file << item._retryCount + qCDebug(lcDb) << "set blacklist entry for " << item._file << item._retryCount << item._errorString << item._lastTryTime << item._ignoreDuration << item._lastTryModtime << item._lastTryEtag << item._renameTarget ; _setErrorBlacklistQuery->reset_and_clear_bindings(); @@ -1560,7 +1562,7 @@ QVector< SyncJournalDb::PollInfo > SyncJournalDb::getPollInfos() if (!query.exec()) { QString err = query.error(); - qDebug() << "Database error :" << query.lastQuery() << ", Error:" << err; + qCDebug(lcDb) << "Database error :" << query.lastQuery() << ", Error:" << err; return res; } @@ -1584,13 +1586,13 @@ void SyncJournalDb::setPollInfo(const SyncJournalDb::PollInfo& info) } if (info._url.isEmpty()) { - qDebug() << "Deleting Poll job" << info._file; + qCDebug(lcDb) << "Deleting Poll job" << info._file; SqlQuery query("DELETE FROM poll WHERE path=?", _db); query.bindValue(1, info._file); if( !query.exec() ) { - qDebug() << "SQL error in setPollInfo: "<< query.error(); + qCDebug(lcDb) << "SQL error in setPollInfo: "<< query.error(); } else { - qDebug() << query.lastQuery() << info._file; + qCDebug(lcDb) << query.lastQuery() << info._file; } } else { SqlQuery query("INSERT OR REPLACE INTO poll (path, modtime, pollpath) VALUES( ? , ? , ? )", _db); @@ -1598,9 +1600,9 @@ void SyncJournalDb::setPollInfo(const SyncJournalDb::PollInfo& info) query.bindValue(2, QString::number(info._modtime)); query.bindValue(3, info._url); if( !query.exec() ) { - qDebug() << "SQL error in setPollInfo: "<< query.error(); + qCDebug(lcDb) << "SQL error in setPollInfo: "<< query.error(); } else { - qDebug() << query.lastQuery() << info._file << info._url; + qCDebug(lcDb) << query.lastQuery() << info._file << info._url; } } } @@ -1619,7 +1621,7 @@ QStringList SyncJournalDb::getSelectiveSyncList(SyncJournalDb::SelectiveSyncList _getSelectiveSyncListQuery->reset_and_clear_bindings(); _getSelectiveSyncListQuery->bindValue(1, int(type)); if (!_getSelectiveSyncListQuery->exec()) { - qWarning() << "SQL query failed: "<< _getSelectiveSyncListQuery->error(); + qCWarning(lcDb) << "SQL query failed: "<< _getSelectiveSyncListQuery->error(); *ok = false; return result; } @@ -1646,7 +1648,7 @@ void SyncJournalDb::setSelectiveSyncList(SyncJournalDb::SelectiveSyncListType ty SqlQuery delQuery("DELETE FROM selectivesync WHERE type == ?1", _db); delQuery.bindValue(1, int(type)); if( !delQuery.exec() ) { - qWarning() << "SQL error when deleting selective sync list" << list << delQuery.error(); + qCWarning(lcDb) << "SQL error when deleting selective sync list" << list << delQuery.error(); } SqlQuery insQuery("INSERT INTO selectivesync VALUES (?1, ?2)" , _db); @@ -1655,7 +1657,7 @@ void SyncJournalDb::setSelectiveSyncList(SyncJournalDb::SelectiveSyncListType ty insQuery.bindValue(1, path); insQuery.bindValue(2, int(type)); if (!insQuery.exec()) { - qWarning() << "SQL error when inserting into selective sync" << type << path << delQuery.error(); + qCWarning(lcDb) << "SQL error when inserting into selective sync" << type << path << delQuery.error(); } } } @@ -1673,9 +1675,9 @@ void SyncJournalDb::avoidRenamesOnNextSync(const QString& path) query.bindValue(1, path); query.bindValue(2, path); if( !query.exec() ) { - qDebug() << Q_FUNC_INFO << "SQL error in avoidRenamesOnNextSync: "<< query.error(); + qCDebug(lcDb) << "SQL error in avoidRenamesOnNextSync: "<< query.error(); } else { - qDebug() << Q_FUNC_INFO << query.lastQuery() << path << "(" << query.numRowsAffected() << " rows)"; + qCDebug(lcDb) << query.lastQuery() << path << "(" << query.numRowsAffected() << " rows)"; } // We also need to remove the ETags so the update phase refreshes the directory paths @@ -1701,9 +1703,9 @@ void SyncJournalDb::avoidReadFromDbOnNextSync(const QString& fileName) query.prepare("UPDATE metadata SET md5='_invalid_' WHERE ?1 LIKE(path||'/%') AND type == 2;"); // CSYNC_FTW_TYPE_DIR == 2 query.bindValue(1, fileName); if( !query.exec() ) { - qDebug() << Q_FUNC_INFO << "SQL error in avoidRenamesOnNextSync: "<< query.error(); + qCDebug(lcDb) << "SQL error in avoidRenamesOnNextSync: "<< query.error(); } else { - qDebug() << Q_FUNC_INFO << query.lastQuery() << fileName << "(" << query.numRowsAffected() << " rows)"; + qCDebug(lcDb) << query.lastQuery() << fileName << "(" << query.numRowsAffected() << " rows)"; } // Prevent future overwrite of the etag for this sync @@ -1723,13 +1725,13 @@ void SyncJournalDb::forceRemoteDiscoveryNextSync() void SyncJournalDb::forceRemoteDiscoveryNextSyncLocked() { - qDebug() << "Forcing remote re-discovery by deleting folder Etags"; + qCDebug(lcDb) << "Forcing remote re-discovery by deleting folder Etags"; SqlQuery deleteRemoteFolderEtagsQuery(_db); deleteRemoteFolderEtagsQuery.prepare("UPDATE metadata SET md5='_invalid_' WHERE type=2;"); if( !deleteRemoteFolderEtagsQuery.exec() ) { - qDebug() << "ERROR: Query failed" << deleteRemoteFolderEtagsQuery.error(); + qCDebug(lcDb) << "ERROR: Query failed" << deleteRemoteFolderEtagsQuery.error(); } else { - qDebug() << "Cleared" << deleteRemoteFolderEtagsQuery.numRowsAffected() << "folder ETags"; + qCDebug(lcDb) << "Cleared" << deleteRemoteFolderEtagsQuery.numRowsAffected() << "folder ETags"; } } @@ -1746,14 +1748,14 @@ QByteArray SyncJournalDb::getChecksumType(int checksumTypeId) query.reset_and_clear_bindings(); query.bindValue(1, checksumTypeId); if( !query.exec() ) { - qWarning() << "Error SQL statement getChecksumType: " + qCWarning(lcDb) << "Error SQL statement getChecksumType: " << query.lastQuery() << " :" << query.error(); return 0; } if( !query.next() ) { - qDebug() << "No checksum type mapping found for" << checksumTypeId; + qCDebug(lcDb) << "No checksum type mapping found for" << checksumTypeId; return 0; } return query.baValue(0); @@ -1769,7 +1771,7 @@ int SyncJournalDb::mapChecksumType(const QByteArray& checksumType) _insertChecksumTypeQuery->reset_and_clear_bindings(); _insertChecksumTypeQuery->bindValue(1, checksumType); if( !_insertChecksumTypeQuery->exec() ) { - qWarning() << "Error SQL statement insertChecksumType: " + qCWarning(lcDb) << "Error SQL statement insertChecksumType: " << _insertChecksumTypeQuery->lastQuery() << " :" << _insertChecksumTypeQuery->error(); return 0; @@ -1779,14 +1781,14 @@ int SyncJournalDb::mapChecksumType(const QByteArray& checksumType) _getChecksumTypeIdQuery->reset_and_clear_bindings(); _getChecksumTypeIdQuery->bindValue(1, checksumType); if( !_getChecksumTypeIdQuery->exec() ) { - qWarning() << "Error SQL statement getChecksumTypeId: " + qCWarning(lcDb) << "Error SQL statement getChecksumTypeId: " << _getChecksumTypeIdQuery->lastQuery() << " :" << _getChecksumTypeIdQuery->error(); return 0; } if( !_getChecksumTypeIdQuery->next() ) { - qDebug() << "No checksum type mapping found for" << checksumType; + qCDebug(lcDb) << "No checksum type mapping found for" << checksumType; return 0; } return _getChecksumTypeIdQuery->intValue(0); @@ -1801,7 +1803,7 @@ QByteArray SyncJournalDb::dataFingerprint() _getDataFingerprintQuery->reset_and_clear_bindings(); if (!_getDataFingerprintQuery->exec()) { - qWarning() << "Error SQL statement dataFingerprint: " + qCWarning(lcDb) << "Error SQL statement dataFingerprint: " << _getDataFingerprintQuery->lastQuery() << " :" << _getDataFingerprintQuery->error(); return QByteArray(); @@ -1822,7 +1824,7 @@ void SyncJournalDb::setDataFingerprint(const QByteArray &dataFingerprint) _setDataFingerprintQuery1->reset_and_clear_bindings(); if (!_setDataFingerprintQuery1->exec()) { - qWarning() << "Error SQL statement setDataFingerprint1: " + qCWarning(lcDb) << "Error SQL statement setDataFingerprint1: " << _setDataFingerprintQuery1->lastQuery() << " :" << _setDataFingerprintQuery1->error(); } @@ -1830,7 +1832,7 @@ void SyncJournalDb::setDataFingerprint(const QByteArray &dataFingerprint) _setDataFingerprintQuery2->reset_and_clear_bindings(); _setDataFingerprintQuery2->bindValue(1, dataFingerprint); if (!_setDataFingerprintQuery2->exec()) { - qWarning() << "Error SQL statement setDataFingerprint2: " + qCWarning(lcDb) << "Error SQL statement setDataFingerprint2: " << _setDataFingerprintQuery2->lastQuery() << " :" << _setDataFingerprintQuery2->error(); } @@ -1841,9 +1843,9 @@ void SyncJournalDb::clearFileTable() SqlQuery query(_db); query.prepare("DELETE FROM metadata;"); if (!query.exec()) { - qWarning() << "SQL error in clearFileTable" << query.error(); + qCWarning(lcDb) << "SQL error in clearFileTable" << query.error(); } else { - qDebug() << query.lastQuery() << "(" << query.numRowsAffected() << " rows)"; + qCDebug(lcDb) << query.lastQuery() << "(" << query.numRowsAffected() << " rows)"; } } @@ -1866,7 +1868,7 @@ void SyncJournalDb::commitIfNeededAndStartNewTransaction(const QString &context) void SyncJournalDb::commitInternal(const QString& context, bool startTrans ) { - qDebug() << Q_FUNC_INFO << "Transaction commit " << context << (startTrans ? "and starting new transaction" : ""); + qCDebug(lcDb) << "Transaction commit " << context << (startTrans ? "and starting new transaction" : ""); commitTransaction(); if( startTrans ) { diff --git a/src/libsync/syncjournalfilerecord.cpp b/src/libsync/syncjournalfilerecord.cpp index a83fe9768..3025a1002 100644 --- a/src/libsync/syncjournalfilerecord.cpp +++ b/src/libsync/syncjournalfilerecord.cpp @@ -17,8 +17,8 @@ #include "utility.h" #include "filesystem.h" +#include #include -#include #ifdef Q_OS_WIN #include @@ -28,6 +28,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcFileRecord, "sync.database.filerecord", QtInfoMsg) + SyncJournalFileRecord::SyncJournalFileRecord() :_inode(0), _type(0), _fileSize(0), _serverHasIgnoredFiles(false) { @@ -55,7 +57,7 @@ SyncJournalFileRecord::SyncJournalFileRecord(const SyncFileItem &item, const QSt FILE_ATTRIBUTE_NORMAL+FILE_FLAG_BACKUP_SEMANTICS, NULL ); if( h == INVALID_HANDLE_VALUE ) { - qWarning() << "Failed to query the 'inode' because CreateFileW failed for file " << localFileName; + qCWarning(lcFileRecord) << "Failed to query the 'inode' because CreateFileW failed for file " << localFileName; } else { BY_HANDLE_FILE_INFORMATION fileInfo; @@ -69,7 +71,7 @@ SyncJournalFileRecord::SyncJournalFileRecord(const SyncFileItem &item, const QSt _inode = FileIndex.QuadPart; } else { - qWarning() << "Failed to query the 'inode' for file " << localFileName; + qCWarning(lcFileRecord) << "Failed to query the 'inode' for file " << localFileName; } CloseHandle(h); @@ -77,12 +79,12 @@ SyncJournalFileRecord::SyncJournalFileRecord(const SyncFileItem &item, const QSt #else struct stat sb; if( stat(QFile::encodeName(localFileName).constData(), &sb) < 0) { - qWarning() << "Failed to query the 'inode' for file " << localFileName; + qCWarning(lcFileRecord) << "Failed to query the 'inode' for file " << localFileName; } else { _inode = sb.st_ino; } #endif - qDebug() << Q_FUNC_INFO << localFileName << "Retrieved inode " << _inode << "(previous item inode: " << item._inode << ")"; + qCDebug(lcFileRecord) << localFileName << "Retrieved inode " << _inode << "(previous item inode: " << item._inode << ")"; } diff --git a/src/libsync/utility.cpp b/src/libsync/utility.cpp index 2a140f89e..1f1139d9e 100644 --- a/src/libsync/utility.cpp +++ b/src/libsync/utility.cpp @@ -26,7 +26,6 @@ #include #include #include -#include #include #include #include @@ -64,6 +63,8 @@ namespace OCC { +Q_LOGGING_CATEGORY(lcUtility, "sync.utility", QtInfoMsg) + bool Utility::writeRandomFile( const QString& fname, int size ) { int maxSize = 10*10*1024; diff --git a/src/libsync/utility.h b/src/libsync/utility.h index 95febc911..c17c7a56c 100644 --- a/src/libsync/utility.h +++ b/src/libsync/utility.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,8 @@ class QSettings; namespace OCC { +Q_DECLARE_LOGGING_CATEGORY(lcUtility) + /** \addtogroup libsync * @{ */ diff --git a/src/libsync/utility_mac.cpp b/src/libsync/utility_mac.cpp index 9ade01adc..19f3042ef 100644 --- a/src/libsync/utility_mac.cpp +++ b/src/libsync/utility_mac.cpp @@ -15,6 +15,8 @@ #include #include +namespace OCC { + static void setupFavLink_private(const QString &folder) { // Finder: Place under "Places"/"Favorites" on the left sidebar @@ -125,3 +127,4 @@ static bool hasDarkSystray_private() return returnValue; } +} // namespace OCC diff --git a/src/libsync/utility_unix.cpp b/src/libsync/utility_unix.cpp index 6eec2fac6..b99c60c7f 100644 --- a/src/libsync/utility_unix.cpp +++ b/src/libsync/utility_unix.cpp @@ -17,6 +17,8 @@ #include #endif +namespace OCC { + static void setupFavLink_private(const QString &folder) { // Nautilus: add to ~/.gtk-bookmarks QFile gtkBookmarks(QDir::homePath()+QLatin1String("/.gtk-bookmarks")); @@ -60,12 +62,12 @@ void setLaunchOnStartup_private(const QString &appName, const QString& guiName, QString desktopFileLocation = userAutoStartPath+appName+QLatin1String(".desktop"); if (enable) { if (!QDir().exists(userAutoStartPath) && !QDir().mkpath(userAutoStartPath)) { - qDebug() << "Could not create autostart folder"; + qCDebug(lcUtility) << "Could not create autostart folder"; return; } QFile iniFile(desktopFileLocation); if (!iniFile.open(QIODevice::WriteOnly)) { - qDebug() << "Could not write auto start entry" << desktopFileLocation; + qCDebug(lcUtility) << "Could not write auto start entry" << desktopFileLocation; return; } QTextStream ts(&iniFile); @@ -83,7 +85,7 @@ void setLaunchOnStartup_private(const QString &appName, const QString& guiName, ; } else { if (!QFile::remove(desktopFileLocation)) { - qDebug() << "Could not remove autostart desktop file"; + qCDebug(lcUtility) << "Could not remove autostart desktop file"; } } } @@ -92,3 +94,5 @@ static inline bool hasDarkSystray_private() { return true; } + +} // namespace OCC diff --git a/src/libsync/utility_win.cpp b/src/libsync/utility_win.cpp index eec0e89ac..bc392d4d7 100644 --- a/src/libsync/utility_win.cpp +++ b/src/libsync/utility_win.cpp @@ -24,7 +24,7 @@ static const char runPathC[] = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"; - +namespace OCC { static void setupFavLink_private(const QString &folder) { @@ -41,9 +41,9 @@ static void setupFavLink_private(const QString &folder) linkName = QDir(links).filePath(folderDir.dirName() + QLatin1String(".lnk")); CoTaskMemFree(path); } - qDebug() << Q_FUNC_INFO << " creating link from " << linkName << " to " << folder; + qCDebug(lcUtility) << " creating link from " << linkName << " to " << folder; if (!QFile::link(folder, linkName)) - qDebug() << Q_FUNC_INFO << "linking" << folder << "to" << linkName << "failed!"; + qCDebug(lcUtility) << "linking" << folder << "to" << linkName << "failed!"; } @@ -71,3 +71,5 @@ static inline bool hasDarkSystray_private() { return true; } + +} // namespace OCC