diff options
| author | Tatsuhiro Tsujikawa <tatsuhiro.t@gmail.com> | 2010-11-20 08:21:36 +0000 |
|---|---|---|
| committer | Tatsuhiro Tsujikawa <tatsuhiro.t@gmail.com> | 2010-11-20 08:21:36 +0000 |
| commit | 580098eb4929a3bdbf424af18da361259ef2efe5 (patch) | |
| tree | c6ff77fa55fcbdcdd0ca21ec2105db14a8c050d3 | |
| parent | 3940da75624b194cdd5036f9fe330fcecc725964 (diff) | |
2010-11-20 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>
Rewritten Logger interface. Logger now writes source file name and
line number in log file.
197 files changed, 2057 insertions, 2698 deletions
@@ -1,3 +1,8 @@ +2010-11-20 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net> + + Rewritten Logger interface. Logger now writes source file name and + line number in log file. + 2010-11-18 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net> Made DHTBucketTreeNode non-copyable. diff --git a/src/AbstractBtMessage.cc b/src/AbstractBtMessage.cc index 07f88f5c..50d2d9c0 100644 --- a/src/AbstractBtMessage.cc +++ b/src/AbstractBtMessage.cc @@ -36,24 +36,21 @@ #include "Peer.h" #include "PieceStorage.h" #include "BtMessageValidator.h" -#include "LogFactory.h" -#include "Logger.h" namespace aria2 { -AbstractBtMessage::AbstractBtMessage(uint8_t id, const std::string& name): - BtMessage(id), - sendingInProgress_(false), - invalidate_(false), - uploading_(false), - cuid_(0), - name_(name), - dispatcher_(0), - messageFactory_(0), - requestFactory_(0), - peerConnection_(0), - metadataGetMode_(false), - logger_(LogFactory::getInstance()) +AbstractBtMessage::AbstractBtMessage(uint8_t id, const std::string& name) + : BtMessage(id), + sendingInProgress_(false), + invalidate_(false), + uploading_(false), + cuid_(0), + name_(name), + dispatcher_(0), + messageFactory_(0), + requestFactory_(0), + peerConnection_(0), + metadataGetMode_(false) {} AbstractBtMessage::~AbstractBtMessage() {} diff --git a/src/AbstractBtMessage.h b/src/AbstractBtMessage.h index 52cd24a3..475cace2 100644 --- a/src/AbstractBtMessage.h +++ b/src/AbstractBtMessage.h @@ -47,7 +47,6 @@ class BtMessageFactory; class BtRequestFactory; class PeerConnection; class BtMessageValidator; -class Logger; class AbstractBtMessage : public BtMessage { private: @@ -73,14 +72,7 @@ private: SharedHandle<BtMessageValidator> validator_; bool metadataGetMode_; - - Logger* logger_; protected: - Logger* getLogger() const - { - return logger_; - } - const SharedHandle<PieceStorage>& getPieceStorage() const { return pieceStorage_; diff --git a/src/AbstractCommand.cc b/src/AbstractCommand.cc index a35d7e25..1c11efc2 100644 --- a/src/AbstractCommand.cc +++ b/src/AbstractCommand.cc @@ -55,6 +55,7 @@ #include "message.h" #include "prefs.h" #include "StringFormat.h" +#include "fmt.h" #include "ServerStat.h" #include "RequestGroupMan.h" #include "A2STR.h" @@ -113,24 +114,20 @@ AbstractCommand::~AbstractCommand() { } bool AbstractCommand::execute() { - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - socket: read:%d, write:%d, hup:%d, err:%d", - util::itos(getCuid()).c_str(), - readEventEnabled(), - writeEventEnabled(), - hupEventEnabled(), - errorEventEnabled()); - } + A2_LOG_DEBUG(fmt("CUID#%s - socket: read:%d, write:%d, hup:%d, err:%d", + util::itos(getCuid()).c_str(), + readEventEnabled(), + writeEventEnabled(), + hupEventEnabled(), + errorEventEnabled())); try { if(requestGroup_->downloadFinished() || requestGroup_->isHaltRequested()) { return true; } if(req_ && req_->removalRequested()) { - if(getLogger()->debug()) { - getLogger()->debug - ("CUID#%s - Discard original URI=%s because it is requested.", - util::itos(getCuid()).c_str(), req_->getUri().c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Discard original URI=%s because it is" + " requested.", + util::itos(getCuid()).c_str(), req_->getUri().c_str())); return prepareForRetry(0); } if(getPieceStorage()) { @@ -140,11 +137,9 @@ bool AbstractCommand::execute() { // This command previously has assigned segments, but it is // canceled. So discard current request chain. Plus, if no // segment is available when http pipelining is used. - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - It seems previously assigned segments" - " are canceled. Restart.", - util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - It seems previously assigned segments" + " are canceled. Restart.", + util::itos(getCuid()).c_str())); // Request::isPipeliningEnabled() == true means aria2 // accessed the remote server and discovered that the server // supports pipelining. @@ -159,12 +154,10 @@ bool AbstractCommand::execute() { !getPieceStorage()->hasMissingUnusedPiece()) { SharedHandle<Request> fasterRequest = fileEntry_->findFasterRequest(req_); if(fasterRequest) { - if(getLogger()->info()) { - getLogger()->info("CUID#%s - Use faster Request hostname=%s, port=%u", - util::itos(getCuid()).c_str(), - fasterRequest->getHost().c_str(), - fasterRequest->getPort()); - } + A2_LOG_INFO(fmt("CUID#%s - Use faster Request hostname=%s, port=%u", + util::itos(getCuid()).c_str(), + fasterRequest->getHost().c_str(), + fasterRequest->getPort())); // Cancel current Request object and use faster one. fileEntry_->removeRequest(req_); Command* command = @@ -206,16 +199,12 @@ bool AbstractCommand::execute() { // TODO socket could be pooled here if pipelining is // enabled... Hmm, I don't think if pipelining is enabled // it does not go here. - if(getLogger()->info()) { - getLogger()->info(MSG_NO_SEGMENT_AVAILABLE, - util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt(MSG_NO_SEGMENT_AVAILABLE, + util::itos(getCuid()).c_str())); // When all segments are ignored in SegmentMan, there are // no URIs available, so don't retry. if(getSegmentMan()->allSegmentsIgnored()) { - if(getLogger()->debug()) { - getLogger()->debug("All segments are ignored."); - } + A2_LOG_DEBUG("All segments are ignored."); return true; } else { return prepareForRetry(1); @@ -247,21 +236,17 @@ bool AbstractCommand::execute() { req_->getProtocol()); ss->setError(); // Purging IP address cache to renew IP address. - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - Marking IP address %s as bad", - util::itos(getCuid()).c_str(), - req_->getConnectedAddr().c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Marking IP address %s as bad", + util::itos(getCuid()).c_str(), + req_->getConnectedAddr().c_str())); e_->markBadIPAddress(req_->getConnectedHostname(), req_->getConnectedAddr(), req_->getConnectedPort()); if(e_->findCachedIPAddress (req_->getConnectedHostname(), req_->getConnectedPort()).empty()) { - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - All IP addresses were marked bad." - " Removing Entry.", - util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - All IP addresses were marked bad." + " Removing Entry.", + util::itos(getCuid()).c_str())); e_->removeCachedIPAddress (req_->getConnectedHostname(), req_->getConnectedPort()); } @@ -272,15 +257,13 @@ bool AbstractCommand::execute() { } } catch(DlAbortEx& err) { if(!req_) { - if(getLogger()->debug()) { - getLogger()->debug(EX_EXCEPTION_CAUGHT, err); - } + A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, err); } else { - getLogger()->error - (MSG_DOWNLOAD_ABORTED, - DL_ABORT_EX2(StringFormat - ("URI=%s", req_->getCurrentUri().c_str()).str(),err), - util::itos(getCuid()).c_str(), req_->getUri().c_str()); + A2_LOG_ERROR_EX(fmt(MSG_DOWNLOAD_ABORTED, + util::itos(getCuid()).c_str(), + req_->getUri().c_str()), + DL_ABORT_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), + err)); fileEntry_->addURIResult(req_->getUri(), err.getCode()); requestGroup_->setLastUriResult(req_->getUri(), err.getCode()); if(err.getCode() == downloadresultcode::CANNOT_RESUME) { @@ -292,27 +275,23 @@ bool AbstractCommand::execute() { return true; } catch(DlRetryEx& err) { assert(req_); - if(getLogger()->info()) { - getLogger()->info - (MSG_RESTARTING_DOWNLOAD, - DL_RETRY_EX2(StringFormat - ("URI=%s", req_->getCurrentUri().c_str()).str(), - err), - util::itos(getCuid()).c_str(), req_->getUri().c_str()); - } + A2_LOG_INFO_EX(fmt(MSG_RESTARTING_DOWNLOAD, + util::itos(getCuid()).c_str(), req_->getUri().c_str()), + DL_RETRY_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), + err)); req_->addTryCount(); req_->resetRedirectCount(); req_->resetUri(); const unsigned int maxTries = getOption()->getAsInt(PREF_MAX_TRIES); bool isAbort = maxTries != 0 && req_->getTryCount() >= maxTries; if(isAbort) { - if(getLogger()->info()) { - getLogger()->info(MSG_MAX_TRY, - util::itos(getCuid()).c_str(), req_->getTryCount()); - } - getLogger()->error(MSG_DOWNLOAD_ABORTED, err, - util::itos(getCuid()).c_str(), - req_->getUri().c_str()); + A2_LOG_INFO(fmt(MSG_MAX_TRY, + util::itos(getCuid()).c_str(), + req_->getTryCount())); + A2_LOG_ERROR_EX(fmt(MSG_DOWNLOAD_ABORTED, + util::itos(getCuid()).c_str(), + req_->getUri().c_str()), + err); fileEntry_->addURIResult(req_->getUri(), err.getCode()); requestGroup_->setLastUriResult(req_->getUri(), err.getCode()); if(err.getCode() == downloadresultcode::CANNOT_RESUME) { @@ -325,7 +304,7 @@ bool AbstractCommand::execute() { return prepareForRetry(0); } } catch(DownloadFailureException& err) { - getLogger()->error(EX_EXCEPTION_CAUGHT, err); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, err); if(req_) { fileEntry_->addURIResult(req_->getUri(), err.getCode()); requestGroup_->setLastUriResult(req_->getUri(), err.getCode()); @@ -343,19 +322,15 @@ void AbstractCommand::tryReserved() { // and there are no URI left. Because file length is unknown, we // can assume that there are no in-flight request object. if(entry->getLength() == 0 && entry->getRemainingUris().empty()) { - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - Not trying next request." - " No reserved/pooled request is remaining and" - " total length is still unknown.", - util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Not trying next request." + " No reserved/pooled request is remaining and" + " total length is still unknown.", + util::itos(getCuid()).c_str())); return; } } - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - Trying reserved/pooled request.", - util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Trying reserved/pooled request.", + util::itos(getCuid()).c_str())); std::vector<Command*> commands; requestGroup_->createNextCommand(commands, e_, 1); e_->setNoWait(true); @@ -368,10 +343,8 @@ bool AbstractCommand::prepareForRetry(time_t wait) { } if(req_) { fileEntry_->poolRequest(req_); - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - Pooling request URI=%s", - util::itos(getCuid()).c_str(), req_->getUri().c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Pooling request URI=%s", + util::itos(getCuid()).c_str(), req_->getUri().c_str())); if(getSegmentMan()) { getSegmentMan()->recognizeSegmentFor(fileEntry_); } @@ -394,10 +367,8 @@ void AbstractCommand::onAbort() { fileEntry_->removeIdenticalURI(req_->getUri()); fileEntry_->removeRequest(req_); } - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - Aborting download", - util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Aborting download", + util::itos(getCuid()).c_str())); if(getPieceStorage()) { getSegmentMan()->cancelSegment(getCuid()); // Don't do following process if BitTorrent is involved or files @@ -414,14 +385,12 @@ void AbstractCommand::onAbort() { // Local file exists, but given servers(or at least contacted // ones) doesn't support resume. Let's restart download from // scratch. - getLogger()->notice("CUID#%s - Failed to resume download." - " Download from scratch.", - util::itos(getCuid()).c_str()); - if(getLogger()->debug()) { - getLogger()->debug - ("CUID#%s - Gathering URIs that has CANNOT_RESUME error", - util::itos(getCuid()).c_str()); - } + A2_LOG_NOTICE(fmt("CUID#%s - Failed to resume download." + " Download from scratch.", + util::itos(getCuid()).c_str())); + A2_LOG_DEBUG(fmt("CUID#%s - Gathering URIs that has CANNOT_RESUME" + " error", + util::itos(getCuid()).c_str())); // Set PREF_ALWAYS_RESUME to A2_V_TRUE to avoid repeating this // process. getOption()->put(PREF_ALWAYS_RESUME, A2_V_TRUE); @@ -435,11 +404,9 @@ void AbstractCommand::onAbort() { uris.reserve(res.size()); std::transform(res.begin(), res.end(), std::back_inserter(uris), std::mem_fun_ref(&URIResult::getURI)); - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - %lu URIs found.", - util::itos(getCuid()).c_str(), - static_cast<unsigned long int>(uris.size())); - } + A2_LOG_DEBUG(fmt("CUID#%s - %lu URIs found.", + util::itos(getCuid()).c_str(), + static_cast<unsigned long int>(uris.size()))); fileEntry_->addUris(uris.begin(), uris.end()); getSegmentMan()->recognizeSegmentFor(fileEntry_); } @@ -640,15 +607,10 @@ SharedHandle<Request> AbstractCommand::createProxyRequest() const if(!proxy.empty()) { proxyRequest.reset(new Request()); if(proxyRequest->setUri(proxy)) { - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - Using proxy", - util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Using proxy", util::itos(getCuid()).c_str())); } else { - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - Failed to parse proxy string", - util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Failed to parse proxy string", + util::itos(getCuid()).c_str())); proxyRequest.reset(); } } @@ -671,10 +633,9 @@ void AbstractCommand::initAsyncNameResolver(const std::string& hostname) family = AF_INET; } asyncNameResolver_.reset(new AsyncNameResolver(family)); - if(getLogger()->info()) { - getLogger()->info(MSG_RESOLVING_HOSTNAME, - util::itos(getCuid()).c_str(), hostname.c_str()); - } + A2_LOG_INFO(fmt(MSG_RESOLVING_HOSTNAME, + util::itos(getCuid()).c_str(), + hostname.c_str())); asyncNameResolver_->resolve(hostname); setNameResolverCheck(asyncNameResolver_); } @@ -759,12 +720,10 @@ std::string AbstractCommand::resolveHostname } res.resolve(addrs, hostname); } - if(getLogger()->info()) { - getLogger()->info(MSG_NAME_RESOLUTION_COMPLETE, - util::itos(getCuid()).c_str(), - hostname.c_str(), - strjoin(addrs.begin(), addrs.end(), ", ").c_str()); - } + A2_LOG_INFO(fmt(MSG_NAME_RESOLUTION_COMPLETE, + util::itos(getCuid()).c_str(), + hostname.c_str(), + strjoin(addrs.begin(), addrs.end(), ", ").c_str())); for(std::vector<std::string>::const_iterator i = addrs.begin(), eoi = addrs.end(); i != eoi; ++i) { e_->cacheIPAddress(hostname, *i, port); @@ -772,11 +731,10 @@ std::string AbstractCommand::resolveHostname ipaddr = e_->findCachedIPAddress(hostname, port); } else { ipaddr = addrs.front(); - if(getLogger()->info()) { - getLogger()->info(MSG_DNS_CACHE_HIT, - util::itos(getCuid()).c_str(), hostname.c_str(), - strjoin(addrs.begin(), addrs.end(), ", ").c_str()); - } + A2_LOG_INFO(fmt(MSG_DNS_CACHE_HIT, + util::itos(getCuid()).c_str(), + hostname.c_str(), + strjoin(addrs.begin(), addrs.end(), ", ").c_str())); } return ipaddr; } @@ -804,11 +762,9 @@ bool AbstractCommand::checkIfConnectionEstablished // See also InitiateConnectionCommand::executeInternal() e_->markBadIPAddress(connectedHostname, connectedAddr, connectedPort); if(!e_->findCachedIPAddress(connectedHostname, connectedPort).empty()) { - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY, - util::itos(getCuid()).c_str(), - connectedAddr.c_str(), connectedPort); - } + A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY, + util::itos(getCuid()).c_str(), + connectedAddr.c_str(), connectedPort)); Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand (getCuid(), req_, fileEntry_, requestGroup_, e_); diff --git a/src/AbstractDiskWriter.cc b/src/AbstractDiskWriter.cc index 2385f7a9..d8429cd6 100644 --- a/src/AbstractDiskWriter.cc +++ b/src/AbstractDiskWriter.cc @@ -47,8 +47,6 @@ #include "File.h" #include "util.h" #include "message.h" -#include "LogFactory.h" -#include "Logger.h" #include "DlAbortEx.h" #include "a2io.h" #include "StringFormat.h" @@ -56,12 +54,12 @@ namespace aria2 { -AbstractDiskWriter::AbstractDiskWriter(const std::string& filename): - filename_(filename), - fd_(-1), - readOnly_(false), - directIOAllowed_(false), - logger_(LogFactory::getInstance()) {} +AbstractDiskWriter::AbstractDiskWriter(const std::string& filename) + : filename_(filename), + fd_(-1), + readOnly_(false), + directIOAllowed_(false) +{} AbstractDiskWriter::~AbstractDiskWriter() { diff --git a/src/AbstractDiskWriter.h b/src/AbstractDiskWriter.h index ea7652c2..aa9de332 100644 --- a/src/AbstractDiskWriter.h +++ b/src/AbstractDiskWriter.h @@ -40,8 +40,6 @@ namespace aria2 { -class Logger; - class AbstractDiskWriter : public DiskWriter { private: std::string filename_; @@ -51,8 +49,6 @@ private: bool directIOAllowed_; - Logger* logger_; - ssize_t writeDataInternal(const unsigned char* data, size_t len); ssize_t readDataInternal(unsigned char* data, size_t len); diff --git a/src/ActivePeerConnectionCommand.cc b/src/ActivePeerConnectionCommand.cc index e718c8bd..6b11e98b 100644 --- a/src/ActivePeerConnectionCommand.cc +++ b/src/ActivePeerConnectionCommand.cc @@ -41,6 +41,7 @@ #include "BtRuntime.h" #include "Peer.h" #include "Logger.h" +#include "LogFactory.h" #include "prefs.h" #include "Option.h" #include "BtConstants.h" @@ -51,6 +52,7 @@ #include "bittorrent_helper.h" #include "wallclock.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -59,12 +61,11 @@ ActivePeerConnectionCommand::ActivePeerConnectionCommand RequestGroup* requestGroup, DownloadEngine* e, time_t interval) - : - Command(cuid), - requestGroup_(requestGroup), - interval_(interval), - e_(e), - numNewConnection_(5) + : Command(cuid), + requestGroup_(requestGroup), + interval_(interval), + e_(e), + numNewConnection_(5) { requestGroup_->increaseNumCommand(); } @@ -141,11 +142,9 @@ void ActivePeerConnectionCommand::connectToPeer(const SharedHandle<Peer>& peer) command->setPeerStorage(peerStorage_); command->setPieceStorage(pieceStorage_); e_->addCommand(command); - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_PEER, - util::itos(getCuid()).c_str(), - peer->getIPAddress().c_str()); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_PEER, + util::itos(getCuid()).c_str(), + peer->getIPAddress().c_str())); } void ActivePeerConnectionCommand::setBtRuntime diff --git a/src/AdaptiveFileAllocationIterator.cc b/src/AdaptiveFileAllocationIterator.cc index 347ae0df..8eeb5f99 100644 --- a/src/AdaptiveFileAllocationIterator.cc +++ b/src/AdaptiveFileAllocationIterator.cc @@ -45,9 +45,11 @@ namespace aria2 { AdaptiveFileAllocationIterator::AdaptiveFileAllocationIterator -(BinaryStream* stream, off_t offset, uint64_t totalLength): - stream_(stream), offset_(offset), totalLength_(totalLength), - logger_(LogFactory::getInstance()) {} +(BinaryStream* stream, off_t offset, uint64_t totalLength) + : stream_(stream), + offset_(offset), + totalLength_(totalLength) +{} AdaptiveFileAllocationIterator::~AdaptiveFileAllocationIterator() {} @@ -56,23 +58,17 @@ void AdaptiveFileAllocationIterator::allocateChunk() if(!allocator_) { #ifdef HAVE_FALLOCATE try { - if(logger_->debug()) { - logger_->debug("Testing file system supports fallocate."); - } + A2_LOG_DEBUG("Testing file system supports fallocate."); if(static_cast<uint64_t>(offset_) < totalLength_) { off_t len = std::min(totalLength_-offset_, static_cast<uint64_t>(4096)); stream_->allocate(offset_, len); offset_ += len; } - if(logger_->debug()) { - logger_->debug("File system supports fallocate."); - } + A2_LOG_DEBUG("File system supports fallocate."); allocator_.reset (new FallocFileAllocationIterator(stream_, offset_, totalLength_)); } catch(RecoverableException& e) { - if(logger_->debug()) { - logger_->debug("File system does not support fallocate."); - } + A2_LOG_DEBUG("File system does not support fallocate."); SharedHandle<SingleFileAllocationIterator> salloc (new SingleFileAllocationIterator(stream_, offset_, totalLength_)); salloc->init(); diff --git a/src/AdaptiveFileAllocationIterator.h b/src/AdaptiveFileAllocationIterator.h index ac7d22a4..8a3f2e3b 100644 --- a/src/AdaptiveFileAllocationIterator.h +++ b/src/AdaptiveFileAllocationIterator.h @@ -40,7 +40,6 @@ namespace aria2 { class BinaryStream; -class Logger; class AdaptiveFileAllocationIterator:public FileAllocationIterator { @@ -52,8 +51,6 @@ private: off_t offset_; uint64_t totalLength_; - - Logger* logger_; public: AdaptiveFileAllocationIterator (BinaryStream* stream, off_t offset, uint64_t totalLength); diff --git a/src/AdaptiveURISelector.cc b/src/AdaptiveURISelector.cc index 16909e23..9a994549 100644 --- a/src/AdaptiveURISelector.cc +++ b/src/AdaptiveURISelector.cc @@ -44,6 +44,7 @@ #include "ServerStatMan.h" #include "ServerStat.h" #include "RequestGroup.h" +#include "Logger.h" #include "LogFactory.h" #include "A2STR.h" #include "prefs.h" @@ -52,6 +53,7 @@ #include "SocketCore.h" #include "FileEntry.h" #include "uri.h" +#include "fmt.h" namespace aria2 { @@ -63,10 +65,9 @@ namespace aria2 { */ AdaptiveURISelector::AdaptiveURISelector -(const SharedHandle<ServerStatMan>& serverStatMan, RequestGroup* requestGroup): - serverStatMan_(serverStatMan), - requestGroup_(requestGroup), - logger_(LogFactory::getInstance()) +(const SharedHandle<ServerStatMan>& serverStatMan, RequestGroup* requestGroup) + : serverStatMan_(serverStatMan), + requestGroup_(requestGroup) { resetCounters(); } @@ -77,10 +78,8 @@ std::string AdaptiveURISelector::select (FileEntry* fileEntry, const std::vector<std::pair<size_t, std::string> >& usedHosts) { - if(logger_->debug()) { - logger_->debug("AdaptiveURISelector: called %d", - requestGroup_->getNumConnection()); - } + A2_LOG_DEBUG(fmt("AdaptiveURISelector: called %d", + requestGroup_->getNumConnection())); std::deque<std::string>& uris = fileEntry->getRemainingUris(); if (uris.empty() && requestGroup_->getNumConnection() <= 1) { // here we know the download will fail, trying to find previously @@ -108,13 +107,13 @@ void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry) std::transform(timeouts.begin(), timeouts.end(), std::back_inserter(uris), std::mem_fun_ref(&URIResult::getURI)); - if(logger_->debug()) { + if(A2_LOG_DEBUG_ENABLED) { for(std::deque<std::string>::const_iterator i = uris.begin(), eoi = uris.end(); i != eoi; ++i) { - logger_->debug("AdaptiveURISelector: will retry server with increased" - " timeout (%ld s): %s", - static_cast<long int>(requestGroup_->getTimeout()), - (*i).c_str()); + A2_LOG_DEBUG(fmt("AdaptiveURISelector: will retry server with increased" + " timeout (%ld s): %s", + static_cast<long int>(requestGroup_->getTimeout()), + (*i).c_str())); } } } @@ -140,10 +139,9 @@ std::string AdaptiveURISelector::selectOne(const std::deque<std::string>& uris) if(getNbTestedServers(uris) < 3) { std::string notTested = getFirstNotTestedUri(uris); if(notTested != A2STR::NIL) { - if(logger_->debug()) { - logger_->debug("AdaptiveURISelector: choosing the first non tested" - " mirror: %s", notTested.c_str()); - } + A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the first non tested" + " mirror: %s", + notTested.c_str())); --nbServerToEvaluate_; return notTested; } @@ -154,21 +152,17 @@ std::string AdaptiveURISelector::selectOne(const std::deque<std::string>& uris) std::string notTested = getFirstNotTestedUri(uris); if(notTested != A2STR::NIL) { /* Here we return the first untested mirror */ - if(logger_->debug()) { - logger_->debug("AdaptiveURISelector: choosing non tested mirror %s" + A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing non tested mirror %s" " for connection #%d", - notTested.c_str(), nbConnections_); - } + notTested.c_str(), nbConnections_)); return notTested; } else { /* Here we return a mirror which need to be tested again */ std::string toReTest = getFirstToTestUri(uris); if(toReTest != A2STR::NIL) { - if(logger_->debug()) { - logger_->debug("AdaptiveURISelector: choosing mirror %s which has" + A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing mirror %s which has" " not been tested recently for connection #%d", - toReTest.c_str(), nbConnections_); - } + toReTest.c_str(), nbConnections_)); return toReTest; } else { return getBestMirror(uris); @@ -191,19 +185,18 @@ std::string AdaptiveURISelector::getBestMirror if (bests.size() < 2) { std::string uri = getMaxDownloadSpeedUri(uris); - if(logger_->debug()) { - logger_->debug("AdaptiveURISelector: choosing the best mirror :" + A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the best mirror :" " %.2fKB/s %s (other mirrors are at least 25%% slower)", - (float) max/1024, uri.c_str()); - } + (float) max/1024, + uri.c_str())); return uri; } else { std::string uri = selectRandomUri(bests); - if(logger_->debug()) { - logger_->debug("AdaptiveURISelector: choosing randomly one of the best" + A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing randomly one of the best" " mirrors (range [%.2fKB/s, %.2fKB/s]): %s", - (float) min/1024, (float) max/1024, uri.c_str()); - } + (float) min/1024, + (float) max/1024, + uri.c_str())); return uri; } } @@ -230,12 +223,17 @@ void AdaptiveURISelector::adjustLowestSpeedLimit unsigned int low_lowest = 4 * 1024; unsigned int max = getMaxDownloadSpeed(uris); if (max > 0 && lowest > max / 4) { - logger_->notice("Lowering lowest-speed-limit since known max speed is too" - " near (new:%d was:%d max:%d)", max / 4, lowest, max); + A2_LOG_NOTICE(fmt("Lowering lowest-speed-limit since known max speed is" + " too near (new:%d was:%d max:%d)", + max / 4, + lowest, + max)); command->setLowestDownloadSpeedLimit(max / 4); } else if (max == 0 && lowest > low_lowest) { - logger_->notice("Lowering lowest-speed-limit since we have no clue about" - " available speed (now:%d was:%d)", low_lowest, lowest); + A2_LOG_NOTICE(fmt("Lowering lowest-speed-limit since we have no clue" + " about available speed (now:%d was:%d)", + low_lowest, + lowest)); command->setLowestDownloadSpeedLimit(low_lowest); } } diff --git a/src/AdaptiveURISelector.h b/src/AdaptiveURISelector.h index 97f7bcf9..b8ac6b75 100644 --- a/src/AdaptiveURISelector.h +++ b/src/AdaptiveURISelector.h @@ -43,7 +43,6 @@ namespace aria2 { class ServerStatMan; class RequestGroup; class ServerStat; -class Logger; class AdaptiveURISelector:public URISelector { private: @@ -55,8 +54,6 @@ private: static const time_t MAX_TIMEOUT = 60; - Logger* logger_; - void mayRetryWithIncreasedTimeout(FileEntry* fileEntry); std::string selectOne(const std::deque<std::string>& uris); diff --git a/src/BtDependency.cc b/src/BtDependency.cc index 8eb6dd8d..47ae8516 100644 --- a/src/BtDependency.cc +++ b/src/BtDependency.cc @@ -48,15 +48,17 @@ #include "bittorrent_helper.h" #include "DlAbortEx.h" #include "StringFormat.h" +#include "fmt.h" #include "FileEntry.h" namespace aria2 { -BtDependency::BtDependency(RequestGroup* dependant, - const SharedHandle<RequestGroup>& dependee): - dependant_(dependant), - dependee_(dependee), - logger_(LogFactory::getInstance()) {} +BtDependency::BtDependency +(RequestGroup* dependant, + const SharedHandle<RequestGroup>& dependee) + : dependant_(dependant), + dependee_(dependee) +{} BtDependency::~BtDependency() {} @@ -136,27 +138,21 @@ bool BtDependency::resolve() } } } catch(RecoverableException& e) { - logger_->error(EX_EXCEPTION_CAUGHT, e); - if(logger_->info()) { - logger_->info("BtDependency for GID#%s failed. Go without Bt.", - util::itos(dependant_->getGID()).c_str()); - } + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); + A2_LOG_INFO(fmt("BtDependency for GID#%s failed. Go without Bt.", + util::itos(dependant_->getGID()).c_str())); return true; } - if(logger_->info()) { - logger_->info("Dependency resolved for GID#%s", - util::itos(dependant_->getGID()).c_str()); - } + A2_LOG_INFO(fmt("Dependency resolved for GID#%s", + util::itos(dependant_->getGID()).c_str())); dependant_->setDownloadContext(context); return true; } else if(dependee_->getNumCommand() == 0) { // dependee_'s download failed. // cut reference here dependee_.reset(); - if(logger_->info()) { - logger_->info("BtDependency for GID#%s failed. Go without Bt.", - util::itos(dependant_->getGID()).c_str()); - } + A2_LOG_INFO(fmt("BtDependency for GID#%s failed. Go without Bt.", + util::itos(dependant_->getGID()).c_str())); return true; } else { return false; diff --git a/src/BtDependency.h b/src/BtDependency.h index 32fe45ad..79bf77d2 100644 --- a/src/BtDependency.h +++ b/src/BtDependency.h @@ -41,14 +41,12 @@ namespace aria2 { class RequestGroup; class Option; -class Logger; class BtDependency : public Dependency { private: RequestGroup* dependant_; SharedHandle<RequestGroup> dependee_; - Logger* logger_; public: BtDependency(RequestGroup* dependant, const SharedHandle<RequestGroup>& dependee); diff --git a/src/BtLeecherStateChoke.cc b/src/BtLeecherStateChoke.cc index 361a3412..0088f825 100644 --- a/src/BtLeecherStateChoke.cc +++ b/src/BtLeecherStateChoke.cc @@ -41,13 +41,14 @@ #include "LogFactory.h" #include "SimpleRandomizer.h" #include "wallclock.h" +#include "fmt.h" namespace aria2 { -BtLeecherStateChoke::BtLeecherStateChoke(): - round_(0), - lastRound_(0), - logger_(LogFactory::getInstance()) {} +BtLeecherStateChoke::BtLeecherStateChoke() + : round_(0), + lastRound_(0) +{} BtLeecherStateChoke::~BtLeecherStateChoke() {} @@ -142,8 +143,8 @@ void BtLeecherStateChoke::plannedOptimisticUnchoke std::random_shuffle(peerEntries.begin(), i, *(SimpleRandomizer::getInstance().get())); (*peerEntries.begin()).enableOptUnchoking(); - logger_->info - ("POU: %s", (*peerEntries.begin()).getPeer()->getIPAddress().c_str()); + A2_LOG_INFO(fmt("POU: %s", + (*peerEntries.begin()).getPeer()->getIPAddress().c_str())); } } @@ -162,9 +163,9 @@ void BtLeecherStateChoke::regularUnchoke(std::vector<PeerEntry>& peerEntries) std::vector<PeerEntry>::iterator peerIter = peerEntries.begin(); for(;peerIter != rest && count; ++peerIter, --count) { (*peerIter).disableChokingRequired(); - logger_->info("RU: %s, dlspd=%u", - (*peerIter).getPeer()->getIPAddress().c_str(), - (*peerIter).getDownloadSpeed()); + A2_LOG_INFO(fmt("RU: %s, dlspd=%u", + (*peerIter).getPeer()->getIPAddress().c_str(), + (*peerIter).getDownloadSpeed())); if((*peerIter).getPeer()->optUnchoking()) { fastOptUnchoker = true; (*peerIter).disableOptUnchoking(); @@ -177,11 +178,11 @@ void BtLeecherStateChoke::regularUnchoke(std::vector<PeerEntry>& peerEntries) eoi = peerEntries.end(); i != eoi; ++i) { if((*i).getPeer()->peerInterested()) { (*i).enableOptUnchoking(); - logger_->info("OU: %s", (*i).getPeer()->getIPAddress().c_str()); + A2_LOG_INFO(fmt("OU: %s", (*i).getPeer()->getIPAddress().c_str())); break; } else { (*i).disableChokingRequired(); - logger_->info("OU: %s", (*i).getPeer()->getIPAddress().c_str()); + A2_LOG_INFO(fmt("OU: %s", (*i).getPeer()->getIPAddress().c_str())); } } } @@ -191,7 +192,7 @@ void BtLeecherStateChoke::executeChoke (const std::vector<SharedHandle<Peer> >& peerSet) { - logger_->info("Leecher state, %d choke round started", round_); + A2_LOG_INFO(fmt("Leecher state, %d choke round started", round_)); lastRound_ = global::wallclock; std::vector<PeerEntry> peerEntries; diff --git a/src/BtLeecherStateChoke.h b/src/BtLeecherStateChoke.h index db22e23a..80a3b9a0 100644 --- a/src/BtLeecherStateChoke.h +++ b/src/BtLeecherStateChoke.h @@ -45,7 +45,6 @@ namespace aria2 { class Peer; -class Logger; class BtLeecherStateChoke { private: @@ -53,8 +52,6 @@ private: Timer lastRound_; - Logger* logger_; - class PeerEntry { private: SharedHandle<Peer> peer_; diff --git a/src/BtPieceMessage.cc b/src/BtPieceMessage.cc index 7f76c209..0c072452 100644 --- a/src/BtPieceMessage.cc +++ b/src/BtPieceMessage.cc @@ -45,6 +45,7 @@ #include "MessageDigestHelper.h" #include "DiskAdaptor.h" #include "Logger.h" +#include "LogFactory.h" #include "Peer.h" #include "Piece.h" #include "PieceStorage.h" @@ -53,6 +54,7 @@ #include "BtRequestFactory.h" #include "PeerConnection.h" #include "StringFormat.h" +#include "fmt.h" #include "DownloadContext.h" namespace aria2 { @@ -60,13 +62,13 @@ namespace aria2 { const std::string BtPieceMessage::NAME("piece"); BtPieceMessage::BtPieceMessage -(size_t index, uint32_t begin, size_t blockLength): - AbstractBtMessage(ID, NAME), - index_(index), - begin_(begin), - blockLength_(blockLength), - block_(0), - rawData_(0) +(size_t index, uint32_t begin, size_t blockLength) + : AbstractBtMessage(ID, NAME), + index_(index), + begin_(begin), + blockLength_(blockLength), + block_(0), + rawData_(0) { setUploading(true); } @@ -107,22 +109,19 @@ void BtPieceMessage::doReceivedAction() getPeer()->snubbing(false); SharedHandle<Piece> piece = getPieceStorage()->getPiece(index_); off_t offset = (off_t)index_*downloadContext_->getPieceLength()+begin_; - if(getLogger()->debug()) { - getLogger()->debug(MSG_PIECE_RECEIVED, - util::itos(getCuid()).c_str(), - static_cast<unsigned long>(index_), - begin_, blockLength_, - static_cast<long long int>(offset), - static_cast<unsigned long>(slot.getBlockIndex())); - } + A2_LOG_DEBUG(fmt(MSG_PIECE_RECEIVED, + util::itos(getCuid()).c_str(), + static_cast<unsigned long>(index_), + begin_, + blockLength_, + static_cast<long long int>(offset), + static_cast<unsigned long>(slot.getBlockIndex()))); getPieceStorage()->getDiskAdaptor()->writeData (block_, blockLength_, offset); piece->completeBlock(slot.getBlockIndex()); - if(getLogger()->debug()) { - getLogger()->debug(MSG_PIECE_BITFIELD, util::itos(getCuid()).c_str(), - util::toHex(piece->getBitfield(), - piece->getBitfieldLength()).c_str()); - } + A2_LOG_DEBUG(fmt(MSG_PIECE_BITFIELD, util::itos(getCuid()).c_str(), + util::toHex(piece->getBitfield(), + piece->getBitfieldLength()).c_str())); piece->updateHash(begin_, block_, blockLength_); getBtMessageDispatcher()->removeOutstandingRequest(slot); if(piece->pieceComplete()) { @@ -134,11 +133,10 @@ void BtPieceMessage::doReceivedAction() } } } else { - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - RequestSlot not found, index=%lu, begin=%u", - util::itos(getCuid()).c_str(), - static_cast<unsigned long>(index_), begin_); - } + A2_LOG_DEBUG(fmt("CUID#%s - RequestSlot not found, index=%lu, begin=%u", + util::itos(getCuid()).c_str(), + static_cast<unsigned long>(index_), + begin_)); } } @@ -173,19 +171,15 @@ void BtPieceMessage::send() } size_t writtenLength; if(!isSendingInProgress()) { - if(getLogger()->info()) { - getLogger()->info(MSG_SEND_PEER_MESSAGE, - util::itos(getCuid()).c_str(), - getPeer()->getIPAddress().c_str(), - getPeer()->getPort(), - toString().c_str()); - } + A2_LOG_INFO(fmt(MSG_SEND_PEER_MESSAGE, + util::itos(getCuid()).c_str(), + getPeer()->getIPAddress().c_str(), + getPeer()->getPort(), + toString().c_str())); unsigned char* msgHdr = createMessageHeader(); size_t msgHdrLen = getMessageHeaderLength(); - if(getLogger()->debug()) { - getLogger()->debug("msglength = %lu bytes", - static_cast<unsigned long>(msgHdrLen+blockLength_)); - } + A2_LOG_DEBUG(fmt("msglength = %lu bytes", + static_cast<unsigned long>(msgHdrLen+blockLength_))); getPeerConnection()->pushBytes(msgHdr, msgHdrLen); getPeerConnection()->sendPendingData(); off_t pieceDataOffset = @@ -226,10 +220,8 @@ std::string BtPieceMessage::toString() const bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece) { if(!getPieceStorage()->isEndGame() && piece->isHashCalculated()) { - if(getLogger()->debug()) { - getLogger()->debug("Hash is available!! index=%lu", - static_cast<unsigned long>(piece->getIndex())); - } + A2_LOG_DEBUG(fmt("Hash is available!! index=%lu", + static_cast<unsigned long>(piece->getIndex()))); return piece->getHashString()==downloadContext_->getPieceHash(piece->getIndex()); } else { @@ -243,22 +235,18 @@ bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece) void BtPieceMessage::onNewPiece(const SharedHandle<Piece>& piece) { - if(getLogger()->info()) { - getLogger()->info(MSG_GOT_NEW_PIECE, - util::itos(getCuid()).c_str(), - static_cast<unsigned long>(piece->getIndex())); - } + A2_LOG_INFO(fmt(MSG_GOT_NEW_PIECE, + util::itos(getCuid()).c_str(), + static_cast<unsigned long>(piece->getIndex()))); getPieceStorage()->completePiece(piece); getPieceStorage()->advertisePiece(getCuid(), piece->getIndex()); } void BtPieceMessage::onWrongPiece(const SharedHandle<Piece>& piece) { - if(getLogger()->info()) { - getLogger()->info(MSG_GOT_WRONG_PIECE, - util::itos(getCuid()).c_str(), - static_cast<unsigned long>(piece->getIndex())); - } + A2_LOG_INFO(fmt(MSG_GOT_WRONG_PIECE, + util::itos(getCuid()).c_str(), + static_cast<unsigned long>(piece->getIndex()))); erasePieceOnDisk(piece); piece->clearAllBlock(); piece->destroyHashContext(); @@ -286,12 +274,11 @@ void BtPieceMessage::onChokingEvent(const BtChokingEvent& event) if(!isInvalidate() && !isSendingInProgress() && !getPeer()->isInAmAllowedIndexSet(index_)) { - if(getLogger()->debug()) { - getLogger()->debug(MSG_REJECT_PIECE_CHOKED, - util::itos(getCuid()).c_str(), - static_cast<unsigned long>(index_), - begin_, blockLength_); - } + A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CHOKED, + util::itos(getCuid()).c_str(), + static_cast<unsigned long>(index_), + begin_, + blockLength_)); if(getPeer()->isFastExtensionEnabled()) { BtMessageHandle rej = getBtMessageFactory()->createRejectMessage @@ -310,12 +297,11 @@ void BtPieceMessage::onCancelSendingPieceEvent index_ == event.getIndex() && begin_ == event.getBegin() && blockLength_ == event.getLength()) { - if(getLogger()->debug()) { - getLogger()->debug(MSG_REJECT_PIECE_CANCEL, - util::itos(getCuid()).c_str(), - static_cast<unsigned long>(index_), - begin_, blockLength_); - } + A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CANCEL, + util::itos(getCuid()).c_str(), + static_cast<unsigned long>(index_), + begin_, + blockLength_)); if(getPeer()->isFastExtensionEnabled()) { BtMessageHandle rej = getBtMessageFactory()->createRejectMessage diff --git a/src/BtPortMessage.cc b/src/BtPortMessage.cc index b66cb5c2..e726017d 100644 --- a/src/BtPortMessage.cc +++ b/src/BtPortMessage.cc @@ -38,6 +38,7 @@ #include "util.h" #include "message.h" #include "Logger.h" +#include "LogFactory.h" #include "Peer.h" #include "DHTNode.h" #include "DHTRoutingTable.h" @@ -45,19 +46,21 @@ #include "DHTTaskFactory.h" #include "DHTTask.h" #include "StringFormat.h" +#include "fmt.h" #include "a2functional.h" namespace aria2 { const std::string BtPortMessage::NAME("port"); -BtPortMessage::BtPortMessage(uint16_t port): - SimpleBtMessage(ID, NAME), port_(port), - localNode_(0), - routingTable_(0), - taskQueue_(0), - taskFactory_(0) - {} +BtPortMessage::BtPortMessage(uint16_t port) + : SimpleBtMessage(ID, NAME), + port_(port), + localNode_(0), + routingTable_(0), + taskQueue_(0), + taskFactory_(0) +{} SharedHandle<BtPortMessage> BtPortMessage::create (const unsigned char* data, size_t dataLength) @@ -73,9 +76,7 @@ void BtPortMessage::doReceivedAction() { if(taskFactory_ && taskQueue_) { if(port_ == 0) { - if(getLogger()->debug()) { - getLogger()->debug("Ignored port 0."); - } + A2_LOG_DEBUG("Ignored port 0."); return; } // node id is random at this point. When ping reply received, new DHTNode @@ -89,12 +90,12 @@ void BtPortMessage::doReceivedAction() } if(routingTable_->countBucket() == 1) { // initiate bootstrap - getLogger()->info("Dispatch node_lookup since too few buckets."); + A2_LOG_INFO("Dispatch node_lookup since too few buckets."); taskQueue_->addImmediateTask (taskFactory_->createNodeLookupTask(localNode_->getID())); } } else { - getLogger()->info + A2_LOG_INFO ("DHT port message received while localhost didn't declare support it."); } } diff --git a/src/BtPostDownloadHandler.cc b/src/BtPostDownloadHandler.cc index 6baace05..00ecea28 100644 --- a/src/BtPostDownloadHandler.cc +++ b/src/BtPostDownloadHandler.cc @@ -37,6 +37,7 @@ #include "RequestGroup.h" #include "Option.h" #include "Logger.h" +#include "LogFactory.h" #include "DownloadHandlerConstants.h" #include "File.h" #include "PieceStorage.h" @@ -46,6 +47,7 @@ #include "Exception.h" #include "DownloadContext.h" #include "download_helper.h" +#include "fmt.h" namespace aria2 { @@ -66,8 +68,8 @@ void BtPostDownloadHandler::getNextRequestGroups (std::vector<SharedHandle<RequestGroup> >& groups, RequestGroup* requestGroup) { - getLogger()->info("Generating RequestGroups for Torrent file %s", - requestGroup->getFirstFilePath().c_str()); + A2_LOG_INFO(fmt("Generating RequestGroups for Torrent file %s", + requestGroup->getFirstFilePath().c_str())); std::string content; try { requestGroup->getPieceStorage()->getDiskAdaptor()->openExistingFile(); diff --git a/src/BtSeederStateChoke.cc b/src/BtSeederStateChoke.cc index ca062a02..c465b346 100644 --- a/src/BtSeederStateChoke.cc +++ b/src/BtSeederStateChoke.cc @@ -41,13 +41,14 @@ #include "LogFactory.h" #include "SimpleRandomizer.h" #include "wallclock.h" +#include "fmt.h" namespace aria2 { -BtSeederStateChoke::BtSeederStateChoke(): - round_(0), - lastRound_(0), - logger_(LogFactory::getInstance()) {} +BtSeederStateChoke::BtSeederStateChoke() + : round_(0), + lastRound_(0) +{} BtSeederStateChoke::~BtSeederStateChoke() {} @@ -123,8 +124,9 @@ void BtSeederStateChoke::unchoke for(std::vector<PeerEntry>::iterator eoi = peers.end(); r != eoi && count; ++r, --count) { (*r).getPeer()->chokingRequired(false); - logger_->info("RU: %s, ulspd=%u", (*r).getPeer()->getIPAddress().c_str(), - (*r).getUploadSpeed()); + A2_LOG_INFO(fmt("RU: %s, ulspd=%u", + (*r).getPeer()->getIPAddress().c_str(), + (*r).getUploadSpeed())); } if(round_ < 2) { @@ -134,7 +136,7 @@ void BtSeederStateChoke::unchoke std::random_shuffle(r, peers.end(), *(SimpleRandomizer::getInstance().get())); (*r).getPeer()->optUnchoking(true); - logger_->info("POU: %s", (*r).getPeer()->getIPAddress().c_str()); + A2_LOG_INFO(fmt("POU: %s", (*r).getPeer()->getIPAddress().c_str())); } } } @@ -153,7 +155,7 @@ void BtSeederStateChoke::executeChoke (const std::vector<SharedHandle<Peer> >& peerSet) { - logger_->info("Seeder state, %d choke round started", round_); + A2_LOG_INFO(fmt("Seeder state, %d choke round started", round_)); lastRound_ = global::wallclock; std::vector<PeerEntry> peerEntries; diff --git a/src/BtSeederStateChoke.h b/src/BtSeederStateChoke.h index 9c30fb92..d6b3da14 100644 --- a/src/BtSeederStateChoke.h +++ b/src/BtSeederStateChoke.h @@ -45,7 +45,6 @@ namespace aria2 { class Peer; -class Logger; class BtSeederStateChoke { private: @@ -53,8 +52,6 @@ private: Timer lastRound_; - Logger* logger_; - class PeerEntry { private: SharedHandle<Peer> peer_; diff --git a/src/BtSetup.cc b/src/BtSetup.cc index 6943a5c6..2851c9a5 100644 --- a/src/BtSetup.cc +++ b/src/BtSetup.cc @@ -83,10 +83,11 @@ #include "DownloadContext.h" #include "PieceStorage.h" #include "PeerStorage.h" +#include "fmt.h" namespace aria2 { -BtSetup::BtSetup():logger_(LogFactory::getInstance()) {} +BtSetup::BtSetup() {} void BtSetup::setup(std::vector<Command*>& commands, RequestGroup* requestGroup, @@ -221,7 +222,7 @@ void BtSetup::setup(std::vector<Command*>& commands, if(option->getAsBool(PREF_BT_ENABLE_LPD) && (metadataGetMode || !torrentAttrs->privateTorrent)) { if(LpdReceiveMessageCommand::getNumInstance() == 0) { - logger_->info("Initializing LpdMessageReceiver."); + A2_LOG_INFO("Initializing LpdMessageReceiver."); SharedHandle<LpdMessageReceiver> receiver (new LpdMessageReceiver(LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT)); bool initialized = false; @@ -245,15 +246,15 @@ void BtSetup::setup(std::vector<Command*>& commands, } } if(initialized) { - logger_->info("LpdMessageReceiver initialized. multicastAddr=%s:%u," - " localAddr=%s", - LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT, - receiver->getLocalAddress().c_str()); + A2_LOG_INFO(fmt("LpdMessageReceiver initialized. multicastAddr=%s:%u," + " localAddr=%s", + LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT, + receiver->getLocalAddress().c_str())); LpdReceiveMessageCommand* cmd = LpdReceiveMessageCommand::getInstance(e, receiver); e->addCommand(cmd); } else { - logger_->info("LpdMessageReceiver not initialized."); + A2_LOG_INFO("LpdMessageReceiver not initialized."); } } if(LpdReceiveMessageCommand::getNumInstance()) { @@ -261,20 +262,20 @@ void BtSetup::setup(std::vector<Command*>& commands, bittorrent::getInfoHash(requestGroup->getDownloadContext()); SharedHandle<LpdMessageReceiver> receiver = LpdReceiveMessageCommand::getInstance()->getLpdMessageReceiver(); - logger_->info("Initializing LpdMessageDispatcher."); + A2_LOG_INFO("Initializing LpdMessageDispatcher."); SharedHandle<LpdMessageDispatcher> dispatcher (new LpdMessageDispatcher (std::string(&infoHash[0], &infoHash[INFO_HASH_LENGTH]), btRuntime->getListenPort(), LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT)); if(dispatcher->init(receiver->getLocalAddress(), /*ttl*/1, /*loop*/0)) { - logger_->info("LpdMessageDispatcher initialized."); + A2_LOG_INFO("LpdMessageDispatcher initialized."); LpdDispatchMessageCommand* cmd = new LpdDispatchMessageCommand(e->newCUID(), dispatcher, e); cmd->setBtRuntime(btRuntime); e->addCommand(cmd); } else { - logger_->info("LpdMessageDispatcher not initialized."); + A2_LOG_INFO("LpdMessageDispatcher not initialized."); } } } diff --git a/src/BtSetup.h b/src/BtSetup.h index 0cbf1306..e44dea69 100644 --- a/src/BtSetup.h +++ b/src/BtSetup.h @@ -40,15 +40,12 @@ namespace aria2 { -class Logger; class RequestGroup; class DownloadEngine; class Option; class Command; class BtSetup { -private: - Logger* logger_; public: BtSetup(); diff --git a/src/BtStopDownloadCommand.cc b/src/BtStopDownloadCommand.cc index aaa47627..59225080 100644 --- a/src/BtStopDownloadCommand.cc +++ b/src/BtStopDownloadCommand.cc @@ -37,8 +37,10 @@ #include "RequestGroup.h" #include "BtRuntime.h" #include "Logger.h" +#include "LogFactory.h" #include "wallclock.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -46,10 +48,10 @@ BtStopDownloadCommand::BtStopDownloadCommand (cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e, - time_t timeout): - TimeBasedCommand(cuid, e, 1), - requestGroup_(requestGroup), - timeout_(timeout) + time_t timeout) + : TimeBasedCommand(cuid, e, 1), + requestGroup_(requestGroup), + timeout_(timeout) {} void BtStopDownloadCommand::preProcess() @@ -58,9 +60,9 @@ void BtStopDownloadCommand::preProcess() enableExit(); } if(checkPoint_.difference(global::wallclock) >= timeout_) { - getLogger()->notice("GID#%s Stop downloading torrent due to" - " --bt-stop-timeout option.", - util::itos(requestGroup_->getGID()).c_str()); + A2_LOG_NOTICE(fmt("GID#%s Stop downloading torrent due to" + " --bt-stop-timeout option.", + util::itos(requestGroup_->getGID()).c_str())); requestGroup_->setForceHaltRequested(true); enableExit(); } diff --git a/src/CheckIntegrityCommand.cc b/src/CheckIntegrityCommand.cc index a9c0ff8d..8a36dddd 100644 --- a/src/CheckIntegrityCommand.cc +++ b/src/CheckIntegrityCommand.cc @@ -37,12 +37,14 @@ #include "DownloadEngine.h" #include "RequestGroup.h" #include "Logger.h" +#include "LogFactory.h" #include "message.h" #include "prefs.h" #include "DownloadContext.h" #include "a2functional.h" #include "RecoverableException.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -69,18 +71,18 @@ bool CheckIntegrityCommand::executeInternal() // needed. getRequestGroup()->enableSaveControlFile(); if(getRequestGroup()->downloadFinished()) { - getLogger()->notice - (MSG_VERIFICATION_SUCCESSFUL, - getRequestGroup()->getDownloadContext()->getBasePath().c_str()); + A2_LOG_NOTICE + (fmt(MSG_VERIFICATION_SUCCESSFUL, + getRequestGroup()->getDownloadContext()->getBasePath().c_str())); std::vector<Command*>* commands = new std::vector<Command*>(); auto_delete_container<std::vector<Command*> > commandsDel(commands); entry_->onDownloadFinished(*commands, getDownloadEngine()); getDownloadEngine()->addCommand(*commands); commands->clear(); } else { - getLogger()->error - (MSG_VERIFICATION_FAILED, - getRequestGroup()->getDownloadContext()->getBasePath().c_str()); + A2_LOG_ERROR + (fmt(MSG_VERIFICATION_FAILED, + getRequestGroup()->getDownloadContext()->getBasePath().c_str())); std::vector<Command*>* commands = new std::vector<Command*>(); auto_delete_container<std::vector<Command*> > commandsDel(commands); entry_->onDownloadIncomplete(*commands, getDownloadEngine()); @@ -98,12 +100,13 @@ bool CheckIntegrityCommand::executeInternal() bool CheckIntegrityCommand::handleException(Exception& e) { getDownloadEngine()->getCheckIntegrityMan()->dropPickedEntry(); - getLogger()->error(MSG_FILE_VALIDATION_FAILURE, e, - util::itos(getCuid()).c_str()); - getLogger()->error - (MSG_DOWNLOAD_NOT_COMPLETE, - util::itos(getCuid()).c_str(), - getRequestGroup()->getDownloadContext()->getBasePath().c_str()); + A2_LOG_ERROR_EX(fmt(MSG_FILE_VALIDATION_FAILURE, + util::itos(getCuid()).c_str()), + e); + A2_LOG_ERROR + (fmt(MSG_DOWNLOAD_NOT_COMPLETE, + util::itos(getCuid()).c_str(), + getRequestGroup()->getDownloadContext()->getBasePath().c_str())); return true; } diff --git a/src/CheckIntegrityDispatcherCommand.cc b/src/CheckIntegrityDispatcherCommand.cc index 9c76e662..8cef2de4 100644 --- a/src/CheckIntegrityDispatcherCommand.cc +++ b/src/CheckIntegrityDispatcherCommand.cc @@ -37,15 +37,17 @@ #include "CheckIntegrityCommand.h" #include "message.h" #include "Logger.h" +#include "LogFactory.h" #include "util.h" +#include "fmt.h" namespace aria2 { CheckIntegrityDispatcherCommand::CheckIntegrityDispatcherCommand (cuid_t cuid, const SharedHandle<CheckIntegrityMan>& fileAllocMan, - DownloadEngine* e):SequentialDispatcherCommand<CheckIntegrityEntry> - (cuid, fileAllocMan, e) + DownloadEngine* e) + : SequentialDispatcherCommand<CheckIntegrityEntry>(cuid, fileAllocMan, e) { setStatusRealtime(); } @@ -54,11 +56,9 @@ Command* CheckIntegrityDispatcherCommand::createCommand (const SharedHandle<CheckIntegrityEntry>& entry) { cuid_t newCUID = getDownloadEngine()->newCUID(); - if(getLogger()->info()) { - getLogger()->info("CUID#%s - Dispatching CheckIntegrityCommand CUID#%s.", - util::itos(getCuid()).c_str(), - util::itos(newCUID).c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - Dispatching CheckIntegrityCommand CUID#%s.", + util::itos(getCuid()).c_str(), + util::itos(newCUID).c_str())); return new CheckIntegrityCommand (newCUID, entry->getRequestGroup(), getDownloadEngine(), entry); } diff --git a/src/Command.cc b/src/Command.cc index 8758f334..82db3178 100644 --- a/src/Command.cc +++ b/src/Command.cc @@ -34,17 +34,17 @@ /* copyright --> */ #include "Command.h" #include "LogFactory.h" -#include "Logger.h" namespace aria2 { -Command::Command(cuid_t cuid):status_(STATUS_INACTIVE), - cuid_(cuid), - logger_(LogFactory::getInstance()), - readEvent_(false), - writeEvent_(false), - errorEvent_(false), - hupEvent_(false) {} +Command::Command(cuid_t cuid) + : status_(STATUS_INACTIVE), + cuid_(cuid), + readEvent_(false), + writeEvent_(false), + errorEvent_(false), + hupEvent_(false) +{} void Command::transitStatus() { diff --git a/src/Command.h b/src/Command.h index 8b724045..a164661d 100644 --- a/src/Command.h +++ b/src/Command.h @@ -39,8 +39,6 @@ namespace aria2 { -class Logger; - typedef int64_t cuid_t; class Command { @@ -56,18 +54,12 @@ private: STATUS status_; cuid_t cuid_; - Logger* logger_; bool readEvent_; bool writeEvent_; bool errorEvent_; bool hupEvent_; protected: - Logger* getLogger() const - { - return logger_; - } - bool readEventEnabled() const { return readEvent_; diff --git a/src/CookieStorage.cc b/src/CookieStorage.cc index 6ebb99cd..d555c72c 100644 --- a/src/CookieStorage.cc +++ b/src/CookieStorage.cc @@ -43,6 +43,7 @@ #include "Logger.h" #include "DlAbortEx.h" #include "StringFormat.h" +#include "fmt.h" #include "NsCookieParser.h" #include "File.h" #include "a2functional.h" @@ -139,7 +140,7 @@ bool CookieStorage::DomainEntry::operator<(const DomainEntry& de) const return key_ < de.key_; } -CookieStorage::CookieStorage():logger_(LogFactory::getInstance()) {} +CookieStorage::CookieStorage() {} CookieStorage::~CookieStorage() {} @@ -326,13 +327,13 @@ bool CookieStorage::load(const std::string& filename, time_t now) char header[16]; // "SQLite format 3" plus \0 std::ifstream s(filename.c_str(), std::ios::binary); if(!s) { - logger_->error("Failed to open cookie file %s", filename.c_str()); + A2_LOG_ERROR(fmt("Failed to open cookie file %s", filename.c_str())); return false; } s.get(header, sizeof(header)); if(!s) { - logger_->error("Failed to read header of cookie file %s", - filename.c_str()); + A2_LOG_ERROR(fmt("Failed to read header of cookie file %s", + filename.c_str())); return false; } try { @@ -342,11 +343,9 @@ bool CookieStorage::load(const std::string& filename, time_t now) try { Sqlite3MozCookieParser(filename).parse(cookies); } catch(RecoverableException& e) { - if(logger_->info()) { - logger_->info(EX_EXCEPTION_CAUGHT, e); - logger_->info("This does not look like Firefox3 cookie file." - " Retrying, assuming it is Chromium cookie file."); - } + A2_LOG_INFO_EX(EX_EXCEPTION_CAUGHT, e); + A2_LOG_INFO("This does not look like Firefox3 cookie file." + " Retrying, assuming it is Chromium cookie file."); // Try chrome cookie format Sqlite3ChromiumCookieParser(filename).parse(cookies); } @@ -362,7 +361,7 @@ bool CookieStorage::load(const std::string& filename, time_t now) } return true; } catch(RecoverableException& e) { - logger_->error("Failed to load cookies from %s", filename.c_str()); + A2_LOG_ERROR(fmt("Failed to load cookies from %s", filename.c_str())); return false; } } @@ -373,7 +372,7 @@ bool CookieStorage::saveNsFormat(const std::string& filename) { std::ofstream o(tempfilename.c_str(), std::ios::binary); if(!o) { - logger_->error("Cannot create cookie file %s", filename.c_str()); + A2_LOG_ERROR(fmt("Cannot create cookie file %s", filename.c_str())); return false; } for(std::deque<DomainEntry>::const_iterator i = domains_.begin(), @@ -382,15 +381,16 @@ bool CookieStorage::saveNsFormat(const std::string& filename) } o.flush(); if(!o) { - logger_->error("Failed to save cookies to %s", filename.c_str()); + A2_LOG_ERROR(fmt("Failed to save cookies to %s", filename.c_str())); return false; } } if(File(tempfilename).renameTo(filename)) { return true; } else { - logger_->error("Could not rename file %s as %s", - tempfilename.c_str(), filename.c_str()); + A2_LOG_ERROR(fmt("Could not rename file %s as %s", + tempfilename.c_str(), + filename.c_str())); return false; } } diff --git a/src/CookieStorage.h b/src/CookieStorage.h index d56be1c0..8e9aa3e6 100644 --- a/src/CookieStorage.h +++ b/src/CookieStorage.h @@ -47,8 +47,6 @@ namespace aria2 { -class Logger; - class CookieStorage { public: @@ -122,8 +120,6 @@ public: private: std::deque<DomainEntry> domains_; - Logger* logger_; - template<typename InputIterator> void storeCookies(InputIterator first, InputIterator last, time_t now) { diff --git a/src/DHTAbstractNodeLookupTask.h b/src/DHTAbstractNodeLookupTask.h index 0922d8fa..f5435ad5 100644 --- a/src/DHTAbstractNodeLookupTask.h +++ b/src/DHTAbstractNodeLookupTask.h @@ -55,6 +55,7 @@ #include "util.h" #include "DHTIDCloser.h" #include "a2functional.h" +#include "fmt.h" namespace aria2 { @@ -102,19 +103,15 @@ private: sendMessage(); } if(inFlightMessage_ == 0) { - if(getLogger()->debug()) { - getLogger()->debug("Finished node_lookup for node ID %s", - util::toHex(targetID_, DHT_ID_LENGTH).c_str()); - } + A2_LOG_DEBUG(fmt("Finished node_lookup for node ID %s", + util::toHex(targetID_, DHT_ID_LENGTH).c_str())); onFinish(); updateBucket(); setFinished(true); } else { - if(getLogger()->debug()) { - getLogger()->debug("%lu in flight message for node ID %s", - static_cast<unsigned long>(inFlightMessage_), - util::toHex(targetID_, DHT_ID_LENGTH).c_str()); - } + A2_LOG_DEBUG(fmt("%lu in flight message for node ID %s", + static_cast<unsigned long>(inFlightMessage_), + util::toHex(targetID_, DHT_ID_LENGTH).c_str())); } } @@ -167,9 +164,7 @@ public: inFlightMessage_ = 0; sendMessage(); if(inFlightMessage_ == 0) { - if(getLogger()->debug()) { - getLogger()->debug("No message was sent in this lookup stage. Finished."); - } + A2_LOG_DEBUG("No message was sent in this lookup stage. Finished."); setFinished(true); } } @@ -191,27 +186,21 @@ public: DHT_ID_LENGTH) != 0) { entries_.push_front(*i); ++count; - if(getLogger()->debug()) { - getLogger()->debug("Received nodes: id=%s, ip=%s", - util::toHex((*i)->node->getID(), - DHT_ID_LENGTH).c_str(), - (*i)->node->getIPAddress().c_str()); - } + A2_LOG_DEBUG(fmt("Received nodes: id=%s, ip=%s", + util::toHex((*i)->node->getID(), + DHT_ID_LENGTH).c_str(), + (*i)->node->getIPAddress().c_str())); } } - if(getLogger()->debug()) { - getLogger()->debug("%lu node lookup entries added.", - static_cast<unsigned long>(count)); - } + A2_LOG_DEBUG(fmt("%lu node lookup entries added.", + static_cast<unsigned long>(count))); std::stable_sort(entries_.begin(), entries_.end(), DHTIDCloser(targetID_)); entries_.erase (std::unique(entries_.begin(), entries_.end(), DerefEqualTo<SharedHandle<DHTNodeLookupEntry> >()), entries_.end()); - if(getLogger()->debug()) { - getLogger()->debug("%lu node lookup entries are unique.", - static_cast<unsigned long>(entries_.size())); - } + A2_LOG_DEBUG(fmt("%lu node lookup entries are unique.", + static_cast<unsigned long>(entries_.size()))); if(entries_.size() > DHTBucket::K) { entries_.erase(entries_.begin()+DHTBucket::K, entries_.end()); } @@ -220,10 +209,8 @@ public: void onTimeout(const SharedHandle<DHTNode>& node) { - if(getLogger()->debug()) { - getLogger()->debug("node lookup message timeout for node ID=%s", - util::toHex(node->getID(), DHT_ID_LENGTH).c_str()); - } + A2_LOG_DEBUG(fmt("node lookup message timeout for node ID=%s", + util::toHex(node->getID(), DHT_ID_LENGTH).c_str())); --inFlightMessage_; for(std::deque<SharedHandle<DHTNodeLookupEntry> >::iterator i = entries_.begin(), eoi = entries_.end(); i != eoi; ++i) { diff --git a/src/DHTAbstractTask.cc b/src/DHTAbstractTask.cc index 076c0596..962f37a4 100644 --- a/src/DHTAbstractTask.cc +++ b/src/DHTAbstractTask.cc @@ -41,14 +41,12 @@ #include "DHTMessageCallback.h" #include "DHTBucket.h" #include "DHTTaskQueue.h" -#include "LogFactory.h" #include "util.h" namespace aria2 { DHTAbstractTask::DHTAbstractTask(): finished_(false), - logger_(LogFactory::getInstance()), routingTable_(0), dispatcher_(0), factory_(0), diff --git a/src/DHTAbstractTask.h b/src/DHTAbstractTask.h index f5ce4c5a..e6b24049 100644 --- a/src/DHTAbstractTask.h +++ b/src/DHTAbstractTask.h @@ -48,14 +48,10 @@ class DHTMessageFactory; class DHTMessage; class DHTTaskQueue; -class Logger; - class DHTAbstractTask:public DHTTask { private: bool finished_; - Logger* logger_; - SharedHandle<DHTNode> localNode_; DHTRoutingTable* routingTable_; @@ -70,11 +66,6 @@ protected: { finished_ = f; } - - Logger* getLogger() const - { - return logger_; - } public: DHTAbstractTask(); diff --git a/src/DHTAutoSaveCommand.cc b/src/DHTAutoSaveCommand.cc index f9b06118..308e72e2 100644 --- a/src/DHTAutoSaveCommand.cc +++ b/src/DHTAutoSaveCommand.cc @@ -49,17 +49,20 @@ #include "Option.h" #include "message.h" #include "Logger.h" +#include "LogFactory.h" #include "a2functional.h" #include "FileEntry.h" #include "DlAbortEx.h" #include "StringFormat.h" +#include "fmt.h" namespace aria2 { DHTAutoSaveCommand::DHTAutoSaveCommand -(cuid_t cuid, DownloadEngine* e, int family, time_t interval): - TimeBasedCommand(cuid, e, interval), - family_(family) {} +(cuid_t cuid, DownloadEngine* e, int family, time_t interval) + : TimeBasedCommand(cuid, e, interval), + family_(family) +{} DHTAutoSaveCommand::~DHTAutoSaveCommand() {} @@ -82,7 +85,7 @@ void DHTAutoSaveCommand::save() std::string dhtFile = getDownloadEngine()->getOption()-> get(family_ == AF_INET? PREF_DHT_FILE_PATH : PREF_DHT_FILE_PATH6); - getLogger()->info("Saving DHT routing table to %s.", dhtFile.c_str()); + A2_LOG_INFO(fmt("Saving DHT routing table to %s.", dhtFile.c_str())); File tempFile(dhtFile+"__temp"); // Removing tempFile is unnecessary because the file is truncated on @@ -118,12 +121,13 @@ void DHTAutoSaveCommand::save() serializer.serialize(o); } if(!tempFile.renameTo(dhtFile)) { - getLogger()->error("Cannot move file from %s to %s.", - tempFile.getPath().c_str(), dhtFile.c_str()); + A2_LOG_ERROR(fmt("Cannot move file from %s to %s.", + tempFile.getPath().c_str(), dhtFile.c_str())); } } catch(RecoverableException& e) { - getLogger()->error("Exception caught while saving DHT routing table to %s", - e, dhtFile.c_str()); + A2_LOG_ERROR_EX(fmt("Exception caught while saving DHT routing table to %s", + dhtFile.c_str()), + e); } } diff --git a/src/DHTBucket.cc b/src/DHTBucket.cc index 258b7ada..ee5d0cae 100644 --- a/src/DHTBucket.cc +++ b/src/DHTBucket.cc @@ -47,26 +47,26 @@ #include "bittorrent_helper.h" #include "bitfield.h" #include "wallclock.h" +#include "fmt.h" namespace aria2 { -DHTBucket::DHTBucket(size_t prefixLength, - const unsigned char* max, const unsigned char* min, - const SharedHandle<DHTNode>& localNode): - prefixLength_(prefixLength), - localNode_(localNode), - lastUpdated_(global::wallclock), - logger_(LogFactory::getInstance()) +DHTBucket::DHTBucket +(size_t prefixLength, + const unsigned char* max, const unsigned char* min, + const SharedHandle<DHTNode>& localNode) + : prefixLength_(prefixLength), + localNode_(localNode), + lastUpdated_(global::wallclock) { memcpy(max_, max, DHT_ID_LENGTH); memcpy(min_, min, DHT_ID_LENGTH); } -DHTBucket::DHTBucket(const SharedHandle<DHTNode>& localNode): - prefixLength_(0), - localNode_(localNode), - lastUpdated_(global::wallclock), - logger_(LogFactory::getInstance()) +DHTBucket::DHTBucket(const SharedHandle<DHTNode>& localNode) + : prefixLength_(0), + localNode_(localNode), + lastUpdated_(global::wallclock) { memset(max_, 0xffu, DHT_ID_LENGTH); memset(min_, 0, DHT_ID_LENGTH); @@ -206,16 +206,14 @@ SharedHandle<DHTBucket> DHTBucket::split() } nodes_ = lNodes; // TODO create toString() and use it. - if(logger_->debug()) { - logger_->debug("New bucket. prefixLength=%u, Range:%s-%s", + A2_LOG_DEBUG(fmt("New bucket. prefixLength=%u, Range:%s-%s", static_cast<unsigned int>(rBucket->getPrefixLength()), util::toHex(rBucket->getMinID(), DHT_ID_LENGTH).c_str(), - util::toHex(rBucket->getMaxID(), DHT_ID_LENGTH).c_str()); - logger_->debug("Existing bucket. prefixLength=%u, Range:%s-%s", + util::toHex(rBucket->getMaxID(), DHT_ID_LENGTH).c_str())); + A2_LOG_DEBUG(fmt("Existing bucket. prefixLength=%u, Range:%s-%s", static_cast<unsigned int>(prefixLength_), util::toHex(getMinID(), DHT_ID_LENGTH).c_str(), - util::toHex(getMaxID(), DHT_ID_LENGTH).c_str()); - } + util::toHex(getMaxID(), DHT_ID_LENGTH).c_str())); return rBucket; } diff --git a/src/DHTBucket.h b/src/DHTBucket.h index 9d71a251..0f4cbceb 100644 --- a/src/DHTBucket.h +++ b/src/DHTBucket.h @@ -48,7 +48,6 @@ namespace aria2 { class DHTNode; -class Logger; class DHTBucket { private: @@ -70,8 +69,6 @@ private: Timer lastUpdated_; - Logger* logger_; - bool isInRange(const unsigned char* nodeID, const unsigned char* max, const unsigned char* min) const; public: diff --git a/src/DHTBucketRefreshTask.cc b/src/DHTBucketRefreshTask.cc index e95c3dc2..7b76138c 100644 --- a/src/DHTBucketRefreshTask.cc +++ b/src/DHTBucketRefreshTask.cc @@ -41,7 +41,9 @@ #include "DHTNodeLookupEntry.h" #include "util.h" #include "Logger.h" +#include "LogFactory.h" #include "DHTMessageCallback.h" +#include "fmt.h" namespace aria2 { @@ -67,8 +69,8 @@ void DHTBucketRefreshTask::startup() task->setTaskQueue(getTaskQueue()); task->setLocalNode(getLocalNode()); - getLogger()->info("Dispating bucket refresh. targetID=%s", - util::toHex(targetID, DHT_ID_LENGTH).c_str()); + A2_LOG_INFO(fmt("Dispating bucket refresh. targetID=%s", + util::toHex(targetID, DHT_ID_LENGTH).c_str())); getTaskQueue()->addPeriodicTask1(task); } } diff --git a/src/DHTConnectionImpl.cc b/src/DHTConnectionImpl.cc index 9a2e44f6..86f04f72 100644 --- a/src/DHTConnectionImpl.cc +++ b/src/DHTConnectionImpl.cc @@ -43,13 +43,14 @@ #include "util.h" #include "Socket.h" #include "SimpleRandomizer.h" +#include "fmt.h" namespace aria2 { -DHTConnectionImpl::DHTConnectionImpl(int family): - socket_(new SocketCore(SOCK_DGRAM)), - family_(family), - logger_(LogFactory::getInstance()) {} +DHTConnectionImpl::DHTConnectionImpl(int family) + : socket_(new SocketCore(SOCK_DGRAM)), + family_(family) +{} DHTConnectionImpl::~DHTConnectionImpl() {} @@ -86,10 +87,11 @@ bool DHTConnectionImpl::bind(uint16_t& port, const std::string& addr) std::pair<std::string, uint16_t> svaddr; socket_->getAddrInfo(svaddr); port = svaddr.second; - logger_->notice("IPv%d DHT: listening to port %d", ipv, port); + A2_LOG_NOTICE(fmt("IPv%d DHT: listening to port %d", ipv, port)); return true; } catch(RecoverableException& e) { - logger_->error("Failed to bind for IPv%d DHT. port=%u", e, ipv, port); + A2_LOG_ERROR_EX(fmt("Failed to bind for IPv%d DHT. port=%u", ipv, port), + e); } return false; } diff --git a/src/DHTConnectionImpl.h b/src/DHTConnectionImpl.h index a7c0b1f6..c05d184c 100644 --- a/src/DHTConnectionImpl.h +++ b/src/DHTConnectionImpl.h @@ -42,15 +42,12 @@ namespace aria2 { class SocketCore; -class Logger; class DHTConnectionImpl:public DHTConnection { private: SharedHandle<SocketCore> socket_; int family_; - - Logger* logger_; public: DHTConnectionImpl(int family); diff --git a/src/DHTEntryPointNameResolveCommand.cc b/src/DHTEntryPointNameResolveCommand.cc index 9f4c1a5f..20f506a7 100644 --- a/src/DHTEntryPointNameResolveCommand.cc +++ b/src/DHTEntryPointNameResolveCommand.cc @@ -47,7 +47,9 @@ #include "DHTTask.h" #include "RequestGroupMan.h" #include "Logger.h" +#include "LogFactory.h" #include "StringFormat.h" +#include "fmt.h" #ifdef ENABLE_ASYNC_DNS #include "AsyncNameResolver.h" #endif // ENABLE_ASYNC_DNS @@ -108,7 +110,7 @@ bool DHTEntryPointNameResolveCommand::execute() return false; } } catch(RecoverableException& e) { - getLogger()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } resolver_->reset(); entryPoints_.pop_front(); @@ -129,7 +131,7 @@ bool DHTEntryPointNameResolveCommand::execute() resolvedEntryPoints_.push_back(p); addPingTask(p); } catch(RecoverableException& e) { - getLogger()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } entryPoints_.pop_front(); } @@ -140,7 +142,7 @@ bool DHTEntryPointNameResolveCommand::execute() taskQueue_->addPeriodicTask1(taskFactory_->createBucketRefreshTask()); } } catch(RecoverableException& e) { - getLogger()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } return true; } @@ -163,20 +165,17 @@ bool DHTEntryPointNameResolveCommand::resolveHostname { switch(resolver->getStatus()) { case AsyncNameResolver::STATUS_READY: - if(getLogger()->info()) { - getLogger()->info(MSG_RESOLVING_HOSTNAME, - util::itos(getCuid()).c_str(), hostname.c_str()); - } + A2_LOG_INFO(fmt(MSG_RESOLVING_HOSTNAME, + util::itos(getCuid()).c_str(), + hostname.c_str())); resolver->resolve(hostname); setNameResolverCheck(resolver); return false; case AsyncNameResolver::STATUS_SUCCESS: - if(getLogger()->info()) { - getLogger()->info(MSG_NAME_RESOLUTION_COMPLETE, - util::itos(getCuid()).c_str(), - resolver->getHostname().c_str(), - resolver->getResolvedAddresses().front().c_str()); - } + A2_LOG_INFO(fmt(MSG_NAME_RESOLUTION_COMPLETE, + util::itos(getCuid()).c_str(), + resolver->getHostname().c_str(), + resolver->getResolvedAddresses().front().c_str())); return true; break; case AsyncNameResolver::STATUS_ERROR: diff --git a/src/DHTGetPeersCommand.cc b/src/DHTGetPeersCommand.cc index f48a6149..96e2a3e5 100644 --- a/src/DHTGetPeersCommand.cc +++ b/src/DHTGetPeersCommand.cc @@ -44,20 +44,23 @@ #include "PeerStorage.h" #include "Peer.h" #include "Logger.h" +#include "LogFactory.h" #include "bittorrent_helper.h" #include "DownloadContext.h" #include "wallclock.h" +#include "fmt.h" namespace aria2 { -DHTGetPeersCommand::DHTGetPeersCommand(cuid_t cuid, - RequestGroup* requestGroup, - DownloadEngine* e): - Command(cuid), - requestGroup_(requestGroup), - e_(e), - numRetry_(0), - lastGetPeerTime_(0) +DHTGetPeersCommand::DHTGetPeersCommand +(cuid_t cuid, + RequestGroup* requestGroup, + DownloadEngine* e) + : Command(cuid), + requestGroup_(requestGroup), + e_(e), + numRetry_(0), + lastGetPeerTime_(0) { requestGroup_->increaseNumCommand(); } @@ -79,11 +82,9 @@ bool DHTGetPeersCommand::execute() (btRuntime_->lessThanMinPeers() && lastGetPeerTime_.difference(global::wallclock) >= GET_PEER_MIN_INTERVAL && !requestGroup_->downloadFinished()))) { - if(getLogger()->debug()) { - getLogger()->debug("Issuing PeerLookup for infoHash=%s", - bittorrent::getInfoHashString - (requestGroup_->getDownloadContext()).c_str()); - } + A2_LOG_DEBUG(fmt("Issuing PeerLookup for infoHash=%s", + bittorrent::getInfoHashString + (requestGroup_->getDownloadContext()).c_str())); task_ = taskFactory_->createPeerLookupTask (requestGroup_->getDownloadContext(), btRuntime_, peerStorage_); taskQueue_->addPeriodicTask2(task_); diff --git a/src/DHTInteractionCommand.cc b/src/DHTInteractionCommand.cc index c67aab2f..101d6a22 100644 --- a/src/DHTInteractionCommand.cc +++ b/src/DHTInteractionCommand.cc @@ -43,14 +43,17 @@ #include "message.h" #include "RequestGroupMan.h" #include "Logger.h" +#include "LogFactory.h" #include "DHTMessageCallback.h" #include "DHTNode.h" +#include "fmt.h" namespace aria2 { -DHTInteractionCommand::DHTInteractionCommand(cuid_t cuid, DownloadEngine* e): - Command(cuid), - e_(e) {} +DHTInteractionCommand::DHTInteractionCommand(cuid_t cuid, DownloadEngine* e) + : Command(cuid), + e_(e) +{} DHTInteractionCommand::~DHTInteractionCommand() { @@ -86,7 +89,7 @@ bool DHTInteractionCommand::execute() try { dispatcher_->sendMessages(); } catch(RecoverableException& e) { - getLogger()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } e_->addCommand(this); return false; diff --git a/src/DHTMessageDispatcherImpl.cc b/src/DHTMessageDispatcherImpl.cc index f786b5fb..cbfe7c64 100644 --- a/src/DHTMessageDispatcherImpl.cc +++ b/src/DHTMessageDispatcherImpl.cc @@ -42,15 +42,16 @@ #include "Logger.h" #include "DHTConstants.h" #include "StringFormat.h" +#include "fmt.h" #include "DHTNode.h" namespace aria2 { DHTMessageDispatcherImpl::DHTMessageDispatcherImpl -(const SharedHandle<DHTMessageTracker>& tracker): - tracker_(tracker), - timeout_(DHT_MESSAGE_TIMEOUT), - logger_(LogFactory::getInstance()) {} +(const SharedHandle<DHTMessageTracker>& tracker) + : tracker_(tracker), + timeout_(DHT_MESSAGE_TIMEOUT) +{} DHTMessageDispatcherImpl::~DHTMessageDispatcherImpl() {} @@ -82,15 +83,14 @@ DHTMessageDispatcherImpl::sendMessage if(!entry->message->isReply()) { tracker_->addMessage(entry->message, entry->timeout, entry->callback); } - if(logger_->info()) { - logger_->info("Message sent: %s", entry->message->toString().c_str()); - } + A2_LOG_INFO(fmt("Message sent: %s", entry->message->toString().c_str())); } else { return false; } } catch(RecoverableException& e) { - logger_->info("Failed to send message: %s", - e, entry->message->toString().c_str()); + A2_LOG_INFO_EX(fmt("Failed to send message: %s", + entry->message->toString().c_str()), + e); // Add message to DHTMessageTracker with timeout 0 to treat it as // time out. Without this, we have untracked message and some of // DHTTask(such as DHTAbstractNodeLookupTask) don't finish @@ -114,10 +114,8 @@ void DHTMessageDispatcherImpl::sendMessages() } } messageQueue_.erase(messageQueue_.begin(), itr); - if(logger_->debug()) { - logger_->debug("%lu dht messages remaining in the queue.", - static_cast<unsigned long>(messageQueue_.size())); - } + A2_LOG_DEBUG(fmt("%lu dht messages remaining in the queue.", + static_cast<unsigned long>(messageQueue_.size()))); } size_t DHTMessageDispatcherImpl::countMessageInQueue() const diff --git a/src/DHTMessageDispatcherImpl.h b/src/DHTMessageDispatcherImpl.h index 953ce7e6..d0f2090e 100644 --- a/src/DHTMessageDispatcherImpl.h +++ b/src/DHTMessageDispatcherImpl.h @@ -42,7 +42,6 @@ namespace aria2 { class DHTMessageTracker; struct DHTMessageEntry; -class Logger; class DHTMessageDispatcherImpl:public DHTMessageDispatcher { private: @@ -52,8 +51,6 @@ private: time_t timeout_; - Logger* logger_; - bool sendMessage(const SharedHandle<DHTMessageEntry>& msg); public: DHTMessageDispatcherImpl(const SharedHandle<DHTMessageTracker>& tracker); diff --git a/src/DHTMessageFactoryImpl.cc b/src/DHTMessageFactoryImpl.cc index b3294800..681d3238 100644 --- a/src/DHTMessageFactoryImpl.cc +++ b/src/DHTMessageFactoryImpl.cc @@ -61,17 +61,18 @@ #include "Peer.h" #include "Logger.h" #include "StringFormat.h" +#include "fmt.h" namespace aria2 { -DHTMessageFactoryImpl::DHTMessageFactoryImpl(int family): - family_(family), - connection_(0), - dispatcher_(0), - routingTable_(0), - peerAnnounceStorage_(0), - tokenTracker_(0), - logger_(LogFactory::getInstance()) {} +DHTMessageFactoryImpl::DHTMessageFactoryImpl(int family) + : family_(family), + connection_(0), + dispatcher_(0), + routingTable_(0), + peerAnnounceStorage_(0), + tokenTracker_(0) +{} DHTMessageFactoryImpl::~DHTMessageFactoryImpl() {} @@ -256,15 +257,11 @@ DHTMessageFactoryImpl::createResponseMessage // for now, just report error message arrived and throw exception. const List* e = getList(dict, DHTUnknownMessage::E); if(e->size() == 2) { - if(logger_->info()) { - logger_->info("Received Error DHT message. code=%s, msg=%s", + A2_LOG_INFO(fmt("Received Error DHT message. code=%s, msg=%s", util::itos(getInteger(e, 0)->i()).c_str(), - util::percentEncode(getString(e, 1)->s()).c_str()); - } + util::percentEncode(getString(e, 1)->s()).c_str())); } else { - if(logger_->debug()) { - logger_->debug("e doesn't have 2 elements."); - } + A2_LOG_DEBUG("e doesn't have 2 elements."); } throw DL_ABORT_EX("Received Error DHT message."); } else if(y->s() != DHTResponseMessage::R) { diff --git a/src/DHTMessageFactoryImpl.h b/src/DHTMessageFactoryImpl.h index 7bc41491..b4ddce27 100644 --- a/src/DHTMessageFactoryImpl.h +++ b/src/DHTMessageFactoryImpl.h @@ -45,7 +45,6 @@ class DHTMessageDispatcher; class DHTRoutingTable; class DHTPeerAnnounceStorage; class DHTTokenTracker; -class Logger; class DHTMessage; class DHTAbstractMessage; @@ -64,8 +63,6 @@ private: DHTPeerAnnounceStorage* peerAnnounceStorage_; DHTTokenTracker* tokenTracker_; - - Logger* logger_; // search node in routingTable. If it is not found, create new one. SharedHandle<DHTNode> getRemoteNode diff --git a/src/DHTMessageReceiver.cc b/src/DHTMessageReceiver.cc index c6d4158d..35f3acc0 100644 --- a/src/DHTMessageReceiver.cc +++ b/src/DHTMessageReceiver.cc @@ -52,12 +52,13 @@ #include "Logger.h" #include "util.h" #include "bencode2.h" +#include "fmt.h" namespace aria2 { -DHTMessageReceiver::DHTMessageReceiver(const SharedHandle<DHTMessageTracker>& tracker): - tracker_(tracker), - logger_(LogFactory::getInstance()) +DHTMessageReceiver::DHTMessageReceiver +(const SharedHandle<DHTMessageTracker>& tracker) + : tracker_(tracker) {} DHTMessageReceiver::~DHTMessageReceiver() {} @@ -84,13 +85,14 @@ SharedHandle<DHTMessage> DHTMessageReceiver::receiveMessage() isReply = true; } } else { - logger_->info("Malformed DHT message. Missing 'y' key. From:%s:%u", - remoteAddr.c_str(), remotePort); + A2_LOG_INFO(fmt("Malformed DHT message. Missing 'y' key. From:%s:%u", + remoteAddr.c_str(), remotePort)); return handleUnknownMessage(data, sizeof(data), remoteAddr, remotePort); } } else { - logger_->info("Malformed DHT message. This is not a bencoded directory." - " From:%s:%u", remoteAddr.c_str(), remotePort); + A2_LOG_INFO(fmt("Malformed DHT message. This is not a bencoded directory." + " From:%s:%u", + remoteAddr.c_str(), remotePort)); return handleUnknownMessage(data, sizeof(data), remoteAddr, remotePort); } if(isReply) { @@ -111,14 +113,14 @@ SharedHandle<DHTMessage> DHTMessageReceiver::receiveMessage() factory_->createQueryMessage(dict, remoteAddr, remotePort); if(*message->getLocalNode() == *message->getRemoteNode()) { // drop message from localnode - logger_->info("Received DHT message from localnode."); + A2_LOG_INFO("Received DHT message from localnode."); return handleUnknownMessage(data, sizeof(data), remoteAddr, remotePort); } onMessageReceived(message); return message; } } catch(RecoverableException& e) { - logger_->info("Exception thrown while receiving DHT message.", e); + A2_LOG_INFO_EX("Exception thrown while receiving DHT message.", e); return handleUnknownMessage(data, sizeof(data), remoteAddr, remotePort); } } @@ -126,9 +128,7 @@ SharedHandle<DHTMessage> DHTMessageReceiver::receiveMessage() void DHTMessageReceiver::onMessageReceived (const SharedHandle<DHTMessage>& message) { - if(logger_->info()) { - logger_->info("Message received: %s", message->toString().c_str()); - } + A2_LOG_INFO(fmt("Message received: %s", message->toString().c_str())); message->validate(); message->doReceivedAction(); message->getRemoteNode()->markGood(); @@ -149,9 +149,7 @@ DHTMessageReceiver::handleUnknownMessage(const unsigned char* data, { SharedHandle<DHTMessage> m = factory_->createUnknownMessage(data, length, remoteAddr, remotePort); - if(logger_->info()) { - logger_->info("Message received: %s", m->toString().c_str()); - } + A2_LOG_INFO(fmt("Message received: %s", m->toString().c_str())); return m; } diff --git a/src/DHTMessageReceiver.h b/src/DHTMessageReceiver.h index 33935cf1..7d7fac2f 100644 --- a/src/DHTMessageReceiver.h +++ b/src/DHTMessageReceiver.h @@ -46,8 +46,6 @@ class DHTConnection; class DHTMessageFactory; class DHTRoutingTable; -class Logger; - class DHTMessageReceiver { private: SharedHandle<DHTMessageTracker> tracker_; @@ -58,8 +56,6 @@ private: SharedHandle<DHTRoutingTable> routingTable_; - Logger* logger_; - SharedHandle<DHTMessage> handleUnknownMessage(const unsigned char* data, size_t length, const std::string& remoteAddr, uint16_t remotePort); diff --git a/src/DHTMessageTracker.cc b/src/DHTMessageTracker.cc index 88ec2db4..5dc7a6b6 100644 --- a/src/DHTMessageTracker.cc +++ b/src/DHTMessageTracker.cc @@ -48,11 +48,11 @@ #include "DlAbortEx.h" #include "DHTConstants.h" #include "StringFormat.h" +#include "fmt.h" namespace aria2 { -DHTMessageTracker::DHTMessageTracker(): - logger_(LogFactory::getInstance()) {} +DHTMessageTracker::DHTMessageTracker() {} DHTMessageTracker::~DHTMessageTracker() {} @@ -71,18 +71,15 @@ DHTMessageTracker::messageArrived throw DL_ABORT_EX(StringFormat("Malformed DHT message. From:%s:%u", ipaddr.c_str(), port).str()); } - if(logger_->debug()) { - logger_->debug("Searching tracker entry for TransactionID=%s, Remote=%s:%u", - util::toHex(tid->s()).c_str(), ipaddr.c_str(), port); - } + A2_LOG_DEBUG(fmt("Searching tracker entry for TransactionID=%s, Remote=%s:%u", + util::toHex(tid->s()).c_str(), + ipaddr.c_str(), port)); for(std::deque<SharedHandle<DHTMessageTrackerEntry> >::iterator i = entries_.begin(), eoi = entries_.end(); i != eoi; ++i) { if((*i)->match(tid->s(), ipaddr, port)) { SharedHandle<DHTMessageTrackerEntry> entry = *i; entries_.erase(i); - if(logger_->debug()) { - logger_->debug("Tracker entry found."); - } + A2_LOG_DEBUG("Tracker entry found."); SharedHandle<DHTNode> targetNode = entry->getTargetNode(); try { SharedHandle<DHTResponseMessage> message = @@ -91,9 +88,7 @@ DHTMessageTracker::messageArrived targetNode->getPort()); int64_t rtt = entry->getElapsedMillis(); - if(logger_->debug()) { - logger_->debug("RTT is %s", util::itos(rtt).c_str()); - } + A2_LOG_DEBUG(fmt("RTT is %s", util::itos(rtt).c_str())); message->getRemoteNode()->updateRTT(rtt); SharedHandle<DHTMessageCallback> callback = entry->getCallback(); return std::make_pair(message, callback); @@ -103,9 +98,7 @@ DHTMessageTracker::messageArrived } } } - if(logger_->debug()) { - logger_->debug("Tracker entry not found."); - } + A2_LOG_DEBUG("Tracker entry not found."); return std::pair<SharedHandle<DHTResponseMessage>, SharedHandle<DHTMessageCallback> >(); } @@ -115,17 +108,13 @@ void DHTMessageTracker::handleTimeoutEntry { try { SharedHandle<DHTNode> node = entry->getTargetNode(); - if(logger_->debug()) { - logger_->debug("Message timeout: To:%s:%u", - node->getIPAddress().c_str(), node->getPort()); - } + A2_LOG_DEBUG(fmt("Message timeout: To:%s:%u", + node->getIPAddress().c_str(), node->getPort())); node->updateRTT(entry->getElapsedMillis()); node->timeout(); if(node->isBad()) { - if(logger_->debug()) { - logger_->debug("Marked bad: %s:%u", - node->getIPAddress().c_str(), node->getPort()); - } + A2_LOG_DEBUG(fmt("Marked bad: %s:%u", + node->getIPAddress().c_str(), node->getPort())); routingTable_->dropNode(node); } SharedHandle<DHTMessageCallback> callback = entry->getCallback(); @@ -133,7 +122,7 @@ void DHTMessageTracker::handleTimeoutEntry callback->onTimeout(node); } } catch(RecoverableException& e) { - logger_->info("Exception thrown while handling timeouts.", e); + A2_LOG_INFO_EX("Exception thrown while handling timeouts.", e); } } diff --git a/src/DHTMessageTracker.h b/src/DHTMessageTracker.h index 4b674661..fae30052 100644 --- a/src/DHTMessageTracker.h +++ b/src/DHTMessageTracker.h @@ -52,7 +52,6 @@ class DHTMessageCallback; class DHTRoutingTable; class DHTMessageFactory; class DHTMessageTrackerEntry; -class Logger; class DHTMessageTracker { private: @@ -62,8 +61,6 @@ private: SharedHandle<DHTMessageFactory> factory_; - Logger* logger_; - void handleTimeoutEntry(const SharedHandle<DHTMessageTrackerEntry>& entry); public: DHTMessageTracker(); diff --git a/src/DHTPeerAnnounceCommand.cc b/src/DHTPeerAnnounceCommand.cc index 96fd3bda..9ab386cf 100644 --- a/src/DHTPeerAnnounceCommand.cc +++ b/src/DHTPeerAnnounceCommand.cc @@ -39,12 +39,14 @@ #include "RecoverableException.h" #include "message.h" #include "Logger.h" +#include "LogFactory.h" namespace aria2 { DHTPeerAnnounceCommand::DHTPeerAnnounceCommand -(cuid_t cuid, DownloadEngine* e, time_t interval): - TimeBasedCommand(cuid, e, interval) {} +(cuid_t cuid, DownloadEngine* e, time_t interval) + : TimeBasedCommand(cuid, e, interval) +{} DHTPeerAnnounceCommand::~DHTPeerAnnounceCommand() {} @@ -61,7 +63,7 @@ void DHTPeerAnnounceCommand::process() try { peerAnnounceStorage_->handleTimeout(); } catch(RecoverableException& e) { - getLogger()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } diff --git a/src/DHTPeerAnnounceStorage.cc b/src/DHTPeerAnnounceStorage.cc index c7bf2426..d5530c9a 100644 --- a/src/DHTPeerAnnounceStorage.cc +++ b/src/DHTPeerAnnounceStorage.cc @@ -48,11 +48,11 @@ #include "util.h" #include "a2functional.h" #include "wallclock.h" +#include "fmt.h" namespace aria2 { -DHTPeerAnnounceStorage::DHTPeerAnnounceStorage(): - logger_(LogFactory::getInstance()) {} +DHTPeerAnnounceStorage::DHTPeerAnnounceStorage() {} DHTPeerAnnounceStorage::~DHTPeerAnnounceStorage() {} @@ -89,11 +89,9 @@ void DHTPeerAnnounceStorage::addPeerAnnounce(const unsigned char* infoHash, const std::string& ipaddr, uint16_t port) { - if(logger_->debug()) { - logger_->debug("Adding %s:%u to peer announce list: infoHash=%s", + A2_LOG_DEBUG(fmt("Adding %s:%u to peer announce list: infoHash=%s", ipaddr.c_str(), port, - util::toHex(infoHash, DHT_ID_LENGTH).c_str()); - } + util::toHex(infoHash, DHT_ID_LENGTH).c_str())); getPeerAnnounceEntry(infoHash)->addPeerAddrEntry(PeerAddrEntry(ipaddr, port)); } @@ -131,25 +129,19 @@ public: void DHTPeerAnnounceStorage::handleTimeout() { - if(logger_->debug()) { - logger_->debug("Now purge peer announces(%lu entries) which are timed out.", - static_cast<unsigned long>(entries_.size())); - } + A2_LOG_DEBUG(fmt("Now purge peer announces(%lu entries) which are timed out.", + static_cast<unsigned long>(entries_.size()))); std::for_each(entries_.begin(), entries_.end(), RemoveStalePeerAddrEntry()); entries_.erase(std::remove_if(entries_.begin(), entries_.end(), mem_fun_sh(&DHTPeerAnnounceEntry::empty)), entries_.end()); - if(logger_->debug()) { - logger_->debug("Currently %lu peer announce entries", - static_cast<unsigned long>(entries_.size())); - } + A2_LOG_DEBUG(fmt("Currently %lu peer announce entries", + static_cast<unsigned long>(entries_.size()))); } void DHTPeerAnnounceStorage::announcePeer() { - if(logger_->debug()) { - logger_->debug("Now announcing peer."); - } + A2_LOG_DEBUG("Now announcing peer."); for(std::deque<SharedHandle<DHTPeerAnnounceEntry> >::iterator i = entries_.begin(), eoi = entries_.end(); i != eoi; ++i) { if((*i)->getLastUpdated(). @@ -158,10 +150,9 @@ void DHTPeerAnnounceStorage::announcePeer() SharedHandle<DHTTask> task = taskFactory_->createPeerAnnounceTask((*i)->getInfoHash()); taskQueue_->addPeriodicTask2(task); - if(logger_->debug()) { - logger_->debug("Added 1 peer announce: infoHash=%s", - util::toHex((*i)->getInfoHash(), DHT_ID_LENGTH).c_str()); - } + A2_LOG_DEBUG + (fmt("Added 1 peer announce: infoHash=%s", + util::toHex((*i)->getInfoHash(), DHT_ID_LENGTH).c_str())); } } } diff --git a/src/DHTPeerAnnounceStorage.h b/src/DHTPeerAnnounceStorage.h index 7928b520..ceae63b1 100644 --- a/src/DHTPeerAnnounceStorage.h +++ b/src/DHTPeerAnnounceStorage.h @@ -48,7 +48,6 @@ class Peer; class DHTPeerAnnounceEntry; class DHTTaskQueue; class DHTTaskFactory; -class Logger; class DHTPeerAnnounceStorage { private: @@ -59,8 +58,6 @@ private: SharedHandle<DHTTaskQueue> taskQueue_; SharedHandle<DHTTaskFactory> taskFactory_; - - Logger* logger_; public: DHTPeerAnnounceStorage(); diff --git a/src/DHTPeerLookupTask.cc b/src/DHTPeerLookupTask.cc index 77d563e4..94c0de12 100644 --- a/src/DHTPeerLookupTask.cc +++ b/src/DHTPeerLookupTask.cc @@ -36,6 +36,7 @@ #include "Peer.h" #include "DHTGetPeersReplyMessage.h" #include "Logger.h" +#include "LogFactory.h" #include "DHTMessageFactory.h" #include "DHTNode.h" #include "DHTNodeLookupEntry.h" @@ -48,13 +49,15 @@ #include "bittorrent_helper.h" #include "DHTPeerLookupTaskCallback.h" #include "DHTQueryMessage.h" +#include "fmt.h" namespace aria2 { DHTPeerLookupTask::DHTPeerLookupTask -(const SharedHandle<DownloadContext>& downloadContext): - DHTAbstractNodeLookupTask<DHTGetPeersReplyMessage> - (bittorrent::getInfoHash(downloadContext)) {} +(const SharedHandle<DownloadContext>& downloadContext) + : DHTAbstractNodeLookupTask<DHTGetPeersReplyMessage> + (bittorrent::getInfoHash(downloadContext)) +{} void DHTPeerLookupTask::getNodesFromMessage @@ -75,8 +78,8 @@ void DHTPeerLookupTask::onReceivedInternal peerStorage_->addPeer(message->getValues()); peers_.insert(peers_.end(), message->getValues().begin(), message->getValues().end()); - getLogger()->info("Received %lu peers.", - static_cast<unsigned long>(message->getValues().size())); + A2_LOG_INFO(fmt("Received %lu peers.", + static_cast<unsigned long>(message->getValues().size()))); } SharedHandle<DHTMessage> DHTPeerLookupTask::createMessage @@ -93,10 +96,8 @@ SharedHandle<DHTMessageCallback> DHTPeerLookupTask::createCallback() void DHTPeerLookupTask::onFinish() { - if(getLogger()->debug()) { - getLogger()->debug("Peer lookup for %s finished", - util::toHex(getTargetID(), DHT_ID_LENGTH).c_str()); - } + A2_LOG_DEBUG(fmt("Peer lookup for %s finished", + util::toHex(getTargetID(), DHT_ID_LENGTH).c_str())); // send announce_peer message to K closest nodes size_t num = DHTBucket::K; for(std::deque<SharedHandle<DHTNodeLookupEntry> >::const_iterator i = diff --git a/src/DHTReplaceNodeTask.cc b/src/DHTReplaceNodeTask.cc index 66fa70c4..321f5821 100644 --- a/src/DHTReplaceNodeTask.cc +++ b/src/DHTReplaceNodeTask.cc @@ -39,17 +39,19 @@ #include "DHTMessageFactory.h" #include "DHTMessageDispatcher.h" #include "Logger.h" +#include "LogFactory.h" #include "DHTPingReplyMessageCallback.h" #include "DHTQueryMessage.h" +#include "fmt.h" namespace aria2 { -DHTReplaceNodeTask::DHTReplaceNodeTask(const SharedHandle<DHTBucket>& bucket, - const SharedHandle<DHTNode>& newNode): - bucket_(bucket), - newNode_(newNode), - numRetry_(0), - timeout_(DHT_MESSAGE_TIMEOUT) +DHTReplaceNodeTask::DHTReplaceNodeTask +(const SharedHandle<DHTBucket>& bucket, const SharedHandle<DHTNode>& newNode) + : bucket_(bucket), + newNode_(newNode), + numRetry_(0), + timeout_(DHT_MESSAGE_TIMEOUT) {} DHTReplaceNodeTask::~DHTReplaceNodeTask() {} @@ -75,8 +77,8 @@ void DHTReplaceNodeTask::sendMessage() void DHTReplaceNodeTask::onReceived(const DHTPingReplyMessage* message) { - getLogger()->info("ReplaceNode: Ping reply received from %s.", - message->getRemoteNode()->toString().c_str()); + A2_LOG_INFO(fmt("ReplaceNode: Ping reply received from %s.", + message->getRemoteNode()->toString().c_str())); setFinished(true); } @@ -84,16 +86,16 @@ void DHTReplaceNodeTask::onTimeout(const SharedHandle<DHTNode>& node) { ++numRetry_; if(numRetry_ >= MAX_RETRY) { - getLogger()->info("ReplaceNode: Ping failed %lu times. Replace %s with %s.", - static_cast<unsigned long>(numRetry_), - node->toString().c_str(), - newNode_->toString().c_str()); + A2_LOG_INFO(fmt("ReplaceNode: Ping failed %lu times. Replace %s with %s.", + static_cast<unsigned long>(numRetry_), + node->toString().c_str(), + newNode_->toString().c_str())); node->markBad(); bucket_->addNode(newNode_); setFinished(true); } else { - getLogger()->info("ReplaceNode: Ping reply timeout from %s. Try once more.", - node->toString().c_str()); + A2_LOG_INFO(fmt("ReplaceNode: Ping reply timeout from %s. Try once more.", + node->toString().c_str())); sendMessage(); } } diff --git a/src/DHTRoutingTable.cc b/src/DHTRoutingTable.cc index bffcad3f..a9fbd157 100644 --- a/src/DHTRoutingTable.cc +++ b/src/DHTRoutingTable.cc @@ -45,6 +45,7 @@ #include "util.h" #include "LogFactory.h" #include "Logger.h" +#include "fmt.h" namespace aria2 { @@ -52,8 +53,7 @@ DHTRoutingTable::DHTRoutingTable(const SharedHandle<DHTNode>& localNode) : localNode_(localNode), root_(new DHTBucketTreeNode (SharedHandle<DHTBucket>(new DHTBucket(localNode_)))), - numBucket_(1), - logger_(LogFactory::getInstance()) + numBucket_(1) {} DHTRoutingTable::~DHTRoutingTable() @@ -73,30 +73,21 @@ bool DHTRoutingTable::addGoodNode(const SharedHandle<DHTNode>& node) bool DHTRoutingTable::addNode(const SharedHandle<DHTNode>& node, bool good) { - if(logger_->debug()) { - logger_->debug("Trying to add node:%s", node->toString().c_str()); - } + A2_LOG_DEBUG(fmt("Trying to add node:%s", node->toString().c_str())); if(*localNode_ == *node) { - if(logger_->debug()) { - logger_->debug("Adding node with the same ID with localnode is not" - " allowed."); - } + A2_LOG_DEBUG("Adding node with the same ID with localnode is not allowed."); return false; } DHTBucketTreeNode* treeNode = dht::findTreeNodeFor(root_, node->getID()); while(1) { const SharedHandle<DHTBucket>& bucket = treeNode->getBucket(); if(bucket->addNode(node)) { - if(logger_->debug()) { - logger_->debug("Added DHTNode."); - } + A2_LOG_DEBUG("Added DHTNode."); return true; } else if(bucket->splitAllowed()) { - if(logger_->debug()) { - logger_->debug("Splitting bucket. Range:%s-%s", + A2_LOG_DEBUG(fmt("Splitting bucket. Range:%s-%s", util::toHex(bucket->getMinID(), DHT_ID_LENGTH).c_str(), - util::toHex(bucket->getMaxID(), DHT_ID_LENGTH).c_str()); - } + util::toHex(bucket->getMaxID(), DHT_ID_LENGTH).c_str())); treeNode->split(); ++numBucket_; if(treeNode->getLeft()->isInRange(node->getID())) { @@ -107,9 +98,7 @@ bool DHTRoutingTable::addNode(const SharedHandle<DHTNode>& node, bool good) } else { if(good) { bucket->cacheNode(node); - if(logger_->debug()) { - logger_->debug("Cached node=%s", node->toString().c_str()); - } + A2_LOG_DEBUG(fmt("Cached node=%s", node->toString().c_str())); } return false; } diff --git a/src/DHTRoutingTable.h b/src/DHTRoutingTable.h index 3c2c7af8..231c4034 100644 --- a/src/DHTRoutingTable.h +++ b/src/DHTRoutingTable.h @@ -49,7 +49,6 @@ class DHTBucket; class DHTTaskQueue; class DHTTaskFactory; class DHTBucketTreeNode; -class Logger; class DHTRoutingTable { private: @@ -63,8 +62,6 @@ private: SharedHandle<DHTTaskFactory> taskFactory_; - Logger* logger_; - bool addNode(const SharedHandle<DHTNode>& node, bool good); public: DHTRoutingTable(const SharedHandle<DHTNode>& localNode); diff --git a/src/DHTSetup.cc b/src/DHTSetup.cc index 2ac7467e..46286186 100644 --- a/src/DHTSetup.cc +++ b/src/DHTSetup.cc @@ -69,10 +69,11 @@ #include "RecoverableException.h" #include "a2functional.h" #include "DownloadEngine.h" +#include "fmt.h" namespace aria2 { -DHTSetup::DHTSetup():logger_(LogFactory::getInstance()) {} +DHTSetup::DHTSetup() {} DHTSetup::~DHTSetup() {} @@ -105,8 +106,10 @@ void DHTSetup::setup deserializer.deserialize(in); localNode = deserializer.getLocalNode(); } catch(RecoverableException& e) { - logger_->error("Exception caught while loading DHT routing table from %s", - e, dhtFile.c_str()); + A2_LOG_ERROR_EX + (fmt("Exception caught while loading DHT routing table from %s", + dhtFile.c_str()), + e); } if(!localNode) { localNode.reset(new DHTNode()); @@ -125,10 +128,8 @@ void DHTSetup::setup } localNode->setPort(port); } - if(logger_->debug()) { - logger_->debug("Initialized local node ID=%s", - util::toHex(localNode->getID(), DHT_ID_LENGTH).c_str()); - } + A2_LOG_DEBUG(fmt("Initialized local node ID=%s", + util::toHex(localNode->getID(), DHT_ID_LENGTH).c_str())); SharedHandle<DHTRoutingTable> routingTable(new DHTRoutingTable(localNode)); SharedHandle<DHTMessageFactoryImpl> factory @@ -240,7 +241,7 @@ void DHTSetup::setup tempCommands->push_back(command); } } else { - logger_->info("No DHT entry point specified."); + A2_LOG_INFO("No DHT entry point specified."); } { DHTInteractionCommand* command = @@ -288,8 +289,9 @@ void DHTSetup::setup commands.insert(commands.end(), tempCommands->begin(), tempCommands->end()); tempCommands->clear(); } catch(RecoverableException& e) { - logger_->error("Exception caught while initializing DHT functionality." - " DHT is disabled.", e); + A2_LOG_ERROR_EX(fmt("Exception caught while initializing DHT functionality." + " DHT is disabled."), + e); if(family == AF_INET) { DHTRegistry::clearData(); } else { diff --git a/src/DHTSetup.h b/src/DHTSetup.h index 40a031c2..1d111fa0 100644 --- a/src/DHTSetup.h +++ b/src/DHTSetup.h @@ -39,13 +39,11 @@ #include <vector> namespace aria2 { -class Logger; + class DownloadEngine; class Command; class DHTSetup { -private: - Logger* logger_; public: DHTSetup(); diff --git a/src/DHTTaskExecutor.cc b/src/DHTTaskExecutor.cc index 7227f17f..87949110 100644 --- a/src/DHTTaskExecutor.cc +++ b/src/DHTTaskExecutor.cc @@ -40,12 +40,13 @@ #include "Logger.h" #include "LogFactory.h" #include "a2functional.h" +#include "fmt.h" namespace aria2 { -DHTTaskExecutor::DHTTaskExecutor(size_t numConcurrent): - numConcurrent_(numConcurrent), - logger_(LogFactory::getInstance()) {} +DHTTaskExecutor::DHTTaskExecutor(size_t numConcurrent) + : numConcurrent_(numConcurrent) +{} DHTTaskExecutor::~DHTTaskExecutor() {} @@ -64,11 +65,9 @@ void DHTTaskExecutor::update() --r; } } - if(logger_->debug()) { - logger_->debug("Executing %u Task(s). Queue has %u task(s).", + A2_LOG_DEBUG(fmt("Executing %u Task(s). Queue has %u task(s).", static_cast<unsigned int>(getExecutingTaskSize()), - static_cast<unsigned int>(getQueueSize())); - } + static_cast<unsigned int>(getQueueSize()))); } } // namespace aria2 diff --git a/src/DHTTaskExecutor.h b/src/DHTTaskExecutor.h index 436c8dff..f43b3dad 100644 --- a/src/DHTTaskExecutor.h +++ b/src/DHTTaskExecutor.h @@ -45,14 +45,12 @@ namespace aria2 { class DHTTask; -class Logger; class DHTTaskExecutor { private: size_t numConcurrent_; std::vector<SharedHandle<DHTTask> > execTasks_; std::deque<SharedHandle<DHTTask> > queue_; - Logger* logger_; public: DHTTaskExecutor(size_t numConcurrent); diff --git a/src/DHTTaskFactoryImpl.cc b/src/DHTTaskFactoryImpl.cc index 3119efb9..d4488560 100644 --- a/src/DHTTaskFactoryImpl.cc +++ b/src/DHTTaskFactoryImpl.cc @@ -38,8 +38,6 @@ #include "DHTMessageDispatcher.h" #include "DHTMessageFactory.h" #include "DHTTaskQueue.h" -#include "LogFactory.h" -#include "Logger.h" #include "DHTPingTask.h" #include "DHTNodeLookupTask.h" #include "DHTBucketRefreshTask.h" @@ -53,13 +51,13 @@ namespace aria2 { -DHTTaskFactoryImpl::DHTTaskFactoryImpl(): - routingTable_(0), - dispatcher_(0), - factory_(0), - taskQueue_(0), - timeout_(DHT_MESSAGE_TIMEOUT), - logger_(LogFactory::getInstance()) {} +DHTTaskFactoryImpl::DHTTaskFactoryImpl() + : routingTable_(0), + dispatcher_(0), + factory_(0), + taskQueue_(0), + timeout_(DHT_MESSAGE_TIMEOUT) +{} DHTTaskFactoryImpl::~DHTTaskFactoryImpl() {} diff --git a/src/DHTTaskFactoryImpl.h b/src/DHTTaskFactoryImpl.h index 032fb0fa..e90219aa 100644 --- a/src/DHTTaskFactoryImpl.h +++ b/src/DHTTaskFactoryImpl.h @@ -46,7 +46,6 @@ class DHTMessageDispatcher; class DHTMessageFactory; class DHTTaskQueue; class DHTAbstractTask; -class Logger; class DHTTaskFactoryImpl:public DHTTaskFactory { private: @@ -62,8 +61,6 @@ private: time_t timeout_; - Logger* logger_; - void setCommonProperty(const SharedHandle<DHTAbstractTask>& task); public: DHTTaskFactoryImpl(); diff --git a/src/DHTTaskQueueImpl.cc b/src/DHTTaskQueueImpl.cc index 02804ece..505fb010 100644 --- a/src/DHTTaskQueueImpl.cc +++ b/src/DHTTaskQueueImpl.cc @@ -43,27 +43,21 @@ namespace { const size_t NUM_CONCURRENT_TASK = 5; } // namespace -DHTTaskQueueImpl::DHTTaskQueueImpl(): - periodicTaskQueue1_(NUM_CONCURRENT_TASK), - periodicTaskQueue2_(NUM_CONCURRENT_TASK), - immediateTaskQueue_(NUM_CONCURRENT_TASK), - logger_(LogFactory::getInstance()) {} +DHTTaskQueueImpl::DHTTaskQueueImpl() + : periodicTaskQueue1_(NUM_CONCURRENT_TASK), + periodicTaskQueue2_(NUM_CONCURRENT_TASK), + immediateTaskQueue_(NUM_CONCURRENT_TASK) +{} DHTTaskQueueImpl::~DHTTaskQueueImpl() {} void DHTTaskQueueImpl::executeTask() { - if(logger_->debug()) { - logger_->debug("Updating periodicTaskQueue1"); - } + A2_LOG_DEBUG("Updating periodicTaskQueue1"); periodicTaskQueue1_.update(); - if(logger_->debug()) { - logger_->debug("Updating periodicTaskQueue2"); - } + A2_LOG_DEBUG("Updating periodicTaskQueue2"); periodicTaskQueue2_.update(); - if(logger_->debug()) { - logger_->debug("Updating immediateTaskQueue"); - } + A2_LOG_DEBUG("Updating immediateTaskQueue"); immediateTaskQueue_.update(); } diff --git a/src/DHTTaskQueueImpl.h b/src/DHTTaskQueueImpl.h index c293bff0..87c0eaf0 100644 --- a/src/DHTTaskQueueImpl.h +++ b/src/DHTTaskQueueImpl.h @@ -40,8 +40,6 @@ namespace aria2 { -class Logger; - class DHTTaskQueueImpl:public DHTTaskQueue { private: DHTTaskExecutor periodicTaskQueue1_; @@ -49,8 +47,6 @@ private: DHTTaskExecutor periodicTaskQueue2_; DHTTaskExecutor immediateTaskQueue_; - - Logger* logger_; public: DHTTaskQueueImpl(); diff --git a/src/DHTTokenUpdateCommand.cc b/src/DHTTokenUpdateCommand.cc index 8253bc88..176cb6a9 100644 --- a/src/DHTTokenUpdateCommand.cc +++ b/src/DHTTokenUpdateCommand.cc @@ -39,13 +39,14 @@ #include "RecoverableException.h" #include "message.h" #include "Logger.h" +#include "LogFactory.h" namespace aria2 { -DHTTokenUpdateCommand::DHTTokenUpdateCommand(cuid_t cuid, - DownloadEngine* e, - time_t interval): - TimeBasedCommand(cuid, e, interval) {} +DHTTokenUpdateCommand::DHTTokenUpdateCommand +(cuid_t cuid, DownloadEngine* e, time_t interval) + : TimeBasedCommand(cuid, e, interval) +{} DHTTokenUpdateCommand::~DHTTokenUpdateCommand() {} @@ -62,7 +63,7 @@ void DHTTokenUpdateCommand::process() try { tokenTracker_->updateTokenSecret(); } catch(RecoverableException& e) { - getLogger()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } diff --git a/src/DefaultBtAnnounce.cc b/src/DefaultBtAnnounce.cc index 5f65d5e7..a7742005 100644 --- a/src/DefaultBtAnnounce.cc +++ b/src/DefaultBtAnnounce.cc @@ -47,6 +47,7 @@ #include "Peer.h" #include "Option.h" #include "StringFormat.h" +#include "fmt.h" #include "A2STR.h" #include "bencode2.h" #include "bittorrent_helper.h" @@ -57,19 +58,18 @@ namespace aria2 { DefaultBtAnnounce::DefaultBtAnnounce (const SharedHandle<DownloadContext>& downloadContext, - const Option* option): - downloadContext_(downloadContext), - trackers_(0), - prevAnnounceTimer_(0), - interval_(DEFAULT_ANNOUNCE_INTERVAL), - minInterval_(DEFAULT_ANNOUNCE_INTERVAL), - userDefinedInterval_(0), - complete_(0), - incomplete_(0), - announceList_(bittorrent::getTorrentAttrs(downloadContext)->announceList), - option_(option), - logger_(LogFactory::getInstance()), - randomizer_(SimpleRandomizer::getInstance()) + const Option* option) + : downloadContext_(downloadContext), + trackers_(0), + prevAnnounceTimer_(0), + interval_(DEFAULT_ANNOUNCE_INTERVAL), + minInterval_(DEFAULT_ANNOUNCE_INTERVAL), + userDefinedInterval_(0), + complete_(0), + incomplete_(0), + announceList_(bittorrent::getTorrentAttrs(downloadContext)->announceList), + option_(option), + randomizer_(SimpleRandomizer::getInstance()) {} DefaultBtAnnounce::~DefaultBtAnnounce() { @@ -218,9 +218,7 @@ void DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, size_t trackerResponseLength) { - if(logger_->debug()) { - logger_->debug("Now processing tracker response."); - } + A2_LOG_DEBUG("Now processing tracker response."); SharedHandle<ValueBase> decodedValue = bencode2::decode(trackerResponse, trackerResponseLength); const Dict* dict = asDict(decodedValue); @@ -234,28 +232,22 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, } const String* warn = asString(dict->get(BtAnnounce::WARNING_MESSAGE)); if(warn) { - logger_->warn(MSG_TRACKER_WARNING_MESSAGE, warn->s().c_str()); + A2_LOG_WARN(fmt(MSG_TRACKER_WARNING_MESSAGE, warn->s().c_str())); } const String* tid = asString(dict->get(BtAnnounce::TRACKER_ID)); if(tid) { trackerId_ = tid->s(); - if(logger_->debug()) { - logger_->debug("Tracker ID:%s", trackerId_.c_str()); - } + A2_LOG_DEBUG(fmt("Tracker ID:%s", trackerId_.c_str())); } const Integer* ival = asInteger(dict->get(BtAnnounce::INTERVAL)); if(ival && ival->i() > 0) { interval_ = ival->i(); - if(logger_->debug()) { - logger_->debug("Interval:%ld", static_cast<long int>(interval_)); - } + A2_LOG_DEBUG(fmt("Interval:%ld", static_cast<long int>(interval_))); } const Integer* mival = asInteger(dict->get(BtAnnounce::MIN_INTERVAL)); if(mival && mival->i() > 0) { minInterval_ = mival->i(); - if(logger_->debug()) { - logger_->debug("Min interval:%ld", static_cast<long int>(minInterval_)); - } + A2_LOG_DEBUG(fmt("Min interval:%ld", static_cast<long int>(minInterval_))); minInterval_ = std::min(minInterval_, interval_); } else { // Use interval as a minInterval if minInterval is not supplied. @@ -264,20 +256,16 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, const Integer* comp = asInteger(dict->get(BtAnnounce::COMPLETE)); if(comp) { complete_ = comp->i(); - if(logger_->debug()) { - logger_->debug("Complete:%d", complete_); - } + A2_LOG_DEBUG(fmt("Complete:%d", complete_)); } const Integer* incomp = asInteger(dict->get(BtAnnounce::INCOMPLETE)); if(incomp) { incomplete_ = incomp->i(); - if(logger_->debug()) { - logger_->debug("Incomplete:%d", incomplete_); - } + A2_LOG_DEBUG(fmt("Incomplete:%d", incomplete_)); } const SharedHandle<ValueBase>& peerData = dict->get(BtAnnounce::PEERS); if(!peerData) { - logger_->info(MSG_NO_PEER_LIST_RECEIVED); + A2_LOG_INFO(MSG_NO_PEER_LIST_RECEIVED); } else { if(!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) { std::vector<SharedHandle<Peer> > peers; @@ -287,7 +275,7 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, } const SharedHandle<ValueBase>& peer6Data = dict->get(BtAnnounce::PEERS6); if(!peer6Data) { - logger_->info("No peers6 received."); + A2_LOG_INFO("No peers6 received."); } else { if(!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) { std::vector<SharedHandle<Peer> > peers; diff --git a/src/DefaultBtAnnounce.h b/src/DefaultBtAnnounce.h index 027dfad8..f2591339 100644 --- a/src/DefaultBtAnnounce.h +++ b/src/DefaultBtAnnounce.h @@ -43,7 +43,6 @@ namespace aria2 { class DownloadContext; class Option; -class Logger; class BtRuntime; class PieceStorage; class PeerStorage; @@ -62,7 +61,6 @@ private: AnnounceList announceList_; std::string trackerId_; const Option* option_; - Logger* logger_; SharedHandle<Randomizer> randomizer_; SharedHandle<BtRuntime> btRuntime_; SharedHandle<PieceStorage> pieceStorage_; diff --git a/src/DefaultBtInteractive.cc b/src/DefaultBtInteractive.cc index 1fe827b8..792cc3d8 100644 --- a/src/DefaultBtInteractive.cc +++ b/src/DefaultBtInteractive.cc @@ -67,6 +67,7 @@ #include "Logger.h" #include "LogFactory.h" #include "StringFormat.h" +#include "fmt.h" #include "RequestGroup.h" #include "RequestGroupMan.h" #include "bittorrent_helper.h" @@ -79,25 +80,23 @@ namespace aria2 { DefaultBtInteractive::DefaultBtInteractive (const SharedHandle<DownloadContext>& downloadContext, const SharedHandle<Peer>& peer) - : - downloadContext_(downloadContext), - peer_(peer), - metadataGetMode_(false), - localNode_(0), - logger_(LogFactory::getInstance()), - allowedFastSetSize_(10), - haveTimer_(global::wallclock), - keepAliveTimer_(global::wallclock), - floodingTimer_(global::wallclock), - inactiveTimer_(global::wallclock), - pexTimer_(global::wallclock), - perSecTimer_(global::wallclock), - keepAliveInterval_(120), - utPexEnabled_(false), - dhtEnabled_(false), - numReceivedMessage_(0), - maxOutstandingRequest_(DEFAULT_MAX_OUTSTANDING_REQUEST), - requestGroupMan_(0) + : downloadContext_(downloadContext), + peer_(peer), + metadataGetMode_(false), + localNode_(0), + allowedFastSetSize_(10), + haveTimer_(global::wallclock), + keepAliveTimer_(global::wallclock), + floodingTimer_(global::wallclock), + inactiveTimer_(global::wallclock), + pexTimer_(global::wallclock), + perSecTimer_(global::wallclock), + keepAliveInterval_(120), + utPexEnabled_(false), + dhtEnabled_(false), + numReceivedMessage_(0), + maxOutstandingRequest_(DEFAULT_MAX_OUTSTANDING_REQUEST), + requestGroupMan_(0) {} DefaultBtInteractive::~DefaultBtInteractive() {} @@ -139,30 +138,22 @@ BtMessageHandle DefaultBtInteractive::receiveHandshake(bool quickReply) { if(message->isFastExtensionSupported()) { peer_->setFastExtensionEnabled(true); - if(logger_->info()) { - logger_->info(MSG_FAST_EXTENSION_ENABLED, util::itos(cuid_).c_str()); - } + A2_LOG_INFO(fmt(MSG_FAST_EXTENSION_ENABLED, util::itos(cuid_).c_str())); } if(message->isExtendedMessagingEnabled()) { peer_->setExtendedMessagingEnabled(true); if(!utPexEnabled_) { extensionMessageRegistry_->removeExtension("ut_pex"); } - if(logger_->info()) { - logger_->info(MSG_EXTENDED_MESSAGING_ENABLED, util::itos(cuid_).c_str()); - } + A2_LOG_INFO(fmt(MSG_EXTENDED_MESSAGING_ENABLED, util::itos(cuid_).c_str())); } if(message->isDHTEnabled()) { peer_->setDHTEnabled(true); - if(logger_->info()) { - logger_->info(MSG_DHT_ENABLED_PEER, util::itos(cuid_).c_str()); - } - } - if(logger_->info()) { - logger_->info(MSG_RECEIVE_PEER_MESSAGE, util::itos(cuid_).c_str(), - peer_->getIPAddress().c_str(), peer_->getPort(), - message->toString().c_str()); + A2_LOG_INFO(fmt(MSG_DHT_ENABLED_PEER, util::itos(cuid_).c_str())); } + A2_LOG_INFO(fmt(MSG_RECEIVE_PEER_MESSAGE, util::itos(cuid_).c_str(), + peer_->getIPAddress().c_str(), peer_->getPort(), + message->toString().c_str())); return message; } @@ -296,11 +287,10 @@ size_t DefaultBtInteractive::receiveMessages() { break; } ++msgcount; - if(logger_->info()) { - logger_->info(MSG_RECEIVE_PEER_MESSAGE, util::itos(cuid_).c_str(), - peer_->getIPAddress().c_str(), peer_->getPort(), - message->toString().c_str()); - } + A2_LOG_INFO(fmt(MSG_RECEIVE_PEER_MESSAGE, + util::itos(cuid_).c_str(), + peer_->getIPAddress().c_str(), peer_->getPort(), + message->toString().c_str())); message->doReceivedAction(); switch(message->getId()) { @@ -338,17 +328,13 @@ size_t DefaultBtInteractive::receiveMessages() { void DefaultBtInteractive::decideInterest() { if(pieceStorage_->hasMissingPiece(peer_)) { if(!peer_->amInterested()) { - if(logger_->debug()) { - logger_->debug(MSG_PEER_INTERESTED, util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt(MSG_PEER_INTERESTED, util::itos(cuid_).c_str())); dispatcher_-> addMessageToQueue(messageFactory_->createInterestedMessage()); } } else { if(peer_->amInterested()) { - if(logger_->debug()) { - logger_->debug(MSG_PEER_NOT_INTERESTED, util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt(MSG_PEER_NOT_INTERESTED, util::itos(cuid_).c_str())); dispatcher_-> addMessageToQueue(messageFactory_->createNotInterestedMessage()); } @@ -425,10 +411,8 @@ void DefaultBtInteractive::cancelAllPiece() { utMetadataRequestTracker_->getAllTrackedIndex(); for(std::vector<size_t>::const_iterator i = metadataRequests.begin(), eoi = metadataRequests.end(); i != eoi; ++i) { - if(logger_->debug()) { - logger_->debug("Cancel metadata: piece=%lu", - static_cast<unsigned long>(*i)); - } + A2_LOG_DEBUG(fmt("Cancel metadata: piece=%lu", + static_cast<unsigned long>(*i))); pieceStorage_->cancelPiece(pieceStorage_->getPiece(*i)); } } diff --git a/src/DefaultBtInteractive.h b/src/DefaultBtInteractive.h index e639e242..fdbd892a 100644 --- a/src/DefaultBtInteractive.h +++ b/src/DefaultBtInteractive.h @@ -58,7 +58,6 @@ class PeerConnection; class ExtensionMessageFactory; class ExtensionMessageRegistry; class DHTNode; -class Logger; class RequestGroupMan; class UTMetadataRequestFactory; class UTMetadataRequestTracker; @@ -126,7 +125,6 @@ private: DHTNode* localNode_; - Logger* logger_; size_t allowedFastSetSize_; Timer haveTimer_; Timer keepAliveTimer_; diff --git a/src/DefaultBtMessageDispatcher.cc b/src/DefaultBtMessageDispatcher.cc index 7732fbb9..92d8d3f7 100644 --- a/src/DefaultBtMessageDispatcher.cc +++ b/src/DefaultBtMessageDispatcher.cc @@ -55,21 +55,20 @@ #include "RequestGroupMan.h" #include "RequestGroup.h" #include "util.h" +#include "fmt.h" namespace aria2 { -DefaultBtMessageDispatcher::DefaultBtMessageDispatcher(): - cuid(0), - messageFactory_(0), - requestGroupMan_(0), - requestTimeout_(0), - logger_(LogFactory::getInstance()) {} +DefaultBtMessageDispatcher::DefaultBtMessageDispatcher() + : cuid(0), + messageFactory_(0), + requestGroupMan_(0), + requestTimeout_(0) +{} DefaultBtMessageDispatcher::~DefaultBtMessageDispatcher() { - if(logger_->debug()) { - logger_->debug("DefaultBtMessageDispatcher::deleted"); - } + A2_LOG_DEBUG("DefaultBtMessageDispatcher::deleted"); } void DefaultBtMessageDispatcher::addMessageToQueue @@ -147,22 +146,19 @@ class AbortOutstandingRequest { private: SharedHandle<Piece> piece_; cuid_t cuid_; - Logger* logger_; public: - AbortOutstandingRequest(const SharedHandle<Piece>& piece, cuid_t cuid): - piece_(piece), - cuid_(cuid), - logger_(LogFactory::getInstance()) {} + AbortOutstandingRequest(const SharedHandle<Piece>& piece, cuid_t cuid) + : piece_(piece), + cuid_(cuid) + {} void operator()(const RequestSlot& slot) const { - if(logger_->debug()) { - logger_->debug(MSG_DELETING_REQUEST_SLOT, + A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT, util::itos(cuid_).c_str(), static_cast<unsigned long>(slot.getIndex()), slot.getBegin(), - static_cast<unsigned long>(slot.getBlockIndex())); - } + static_cast<unsigned long>(slot.getBlockIndex()))); piece_->cancelBlock(slot.getBlockIndex()); } }; @@ -196,26 +192,24 @@ private: cuid_t cuid_; SharedHandle<Peer> peer_; SharedHandle<PieceStorage> pieceStorage_; - Logger* logger_; public: - ProcessChokedRequestSlot(cuid_t cuid, - const SharedHandle<Peer>& peer, - const SharedHandle<PieceStorage>& pieceStorage): - cuid_(cuid), - peer_(peer), - pieceStorage_(pieceStorage), - logger_(LogFactory::getInstance()) {} + ProcessChokedRequestSlot + (cuid_t cuid, + const SharedHandle<Peer>& peer, + const SharedHandle<PieceStorage>& pieceStorage) + : cuid_(cuid), + peer_(peer), + pieceStorage_(pieceStorage) + {} void operator()(const RequestSlot& slot) const { if(!peer_->isInPeerAllowedIndexSet(slot.getIndex())) { - if(logger_->debug()) { - logger_->debug(MSG_DELETING_REQUEST_SLOT_CHOKED, + A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_CHOKED, util::itos(cuid_).c_str(), static_cast<unsigned long>(slot.getIndex()), slot.getBegin(), - static_cast<unsigned long>(slot.getBlockIndex())); - } + static_cast<unsigned long>(slot.getBlockIndex()))); SharedHandle<Piece> piece = pieceStorage_->getPiece(slot.getIndex()); piece->cancelBlock(slot.getBlockIndex()); } @@ -270,41 +264,37 @@ private: BtMessageDispatcher* messageDispatcher_; BtMessageFactory* messageFactory_; time_t requestTimeout_; - Logger* logger_; public: - ProcessStaleRequestSlot(cuid_t cuid, const SharedHandle<Peer>& peer, - const SharedHandle<PieceStorage>& pieceStorage, - BtMessageDispatcher* dispatcher, - BtMessageFactory* factory, - time_t requestTimeout): - cuid_(cuid), - peer_(peer), - pieceStorage_(pieceStorage), - messageDispatcher_(dispatcher), - messageFactory_(factory), - requestTimeout_(requestTimeout), - logger_(LogFactory::getInstance()) {} + ProcessStaleRequestSlot + (cuid_t cuid, const SharedHandle<Peer>& peer, + const SharedHandle<PieceStorage>& pieceStorage, + BtMessageDispatcher* dispatcher, + BtMessageFactory* factory, + time_t requestTimeout) + : cuid_(cuid), + peer_(peer), + pieceStorage_(pieceStorage), + messageDispatcher_(dispatcher), + messageFactory_(factory), + requestTimeout_(requestTimeout) + {} void operator()(const RequestSlot& slot) { if(slot.isTimeout(requestTimeout_)) { - if(logger_->debug()) { - logger_->debug(MSG_DELETING_REQUEST_SLOT_TIMEOUT, + A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_TIMEOUT, util::itos(cuid_).c_str(), static_cast<unsigned long>(slot.getIndex()), slot.getBegin(), - static_cast<unsigned long>(slot.getBlockIndex())); - } + static_cast<unsigned long>(slot.getBlockIndex()))); slot.getPiece()->cancelBlock(slot.getBlockIndex()); peer_->snubbing(true); } else if(slot.getPiece()->hasBlock(slot.getBlockIndex())) { - if(logger_->debug()) { - logger_->debug(MSG_DELETING_REQUEST_SLOT_ACQUIRED, + A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_ACQUIRED, util::itos(cuid_).c_str(), static_cast<unsigned long>(slot.getIndex()), slot.getBegin(), - static_cast<unsigned long>(slot.getBlockIndex())); - } + static_cast<unsigned long>(slot.getBlockIndex()))); messageDispatcher_->addMessageToQueue (messageFactory_->createCancelMessage(slot.getIndex(), slot.getBegin(), diff --git a/src/DefaultBtMessageDispatcher.h b/src/DefaultBtMessageDispatcher.h index 4f5e73d8..40b80192 100644 --- a/src/DefaultBtMessageDispatcher.h +++ b/src/DefaultBtMessageDispatcher.h @@ -51,7 +51,6 @@ class BtMessage; class BtMessageFactory; class Peer; class Piece; -class Logger; class RequestGroupMan; class DefaultBtMessageDispatcher : public BtMessageDispatcher { @@ -66,7 +65,6 @@ private: SharedHandle<Peer> peer_; RequestGroupMan* requestGroupMan_; time_t requestTimeout_; - Logger* logger_; public: DefaultBtMessageDispatcher(); diff --git a/src/DefaultBtMessageReceiver.h b/src/DefaultBtMessageReceiver.h index 663610c0..5ccb8473 100644 --- a/src/DefaultBtMessageReceiver.h +++ b/src/DefaultBtMessageReceiver.h @@ -45,7 +45,6 @@ class Peer; class PeerConnection; class BtMessageDispatcher; class BtMessageFactory; -class Logger; class DefaultBtMessageReceiver : public BtMessageReceiver { private: diff --git a/src/DefaultBtProgressInfoFile.cc b/src/DefaultBtProgressInfoFile.cc index a662465d..fae1057d 100644 --- a/src/DefaultBtProgressInfoFile.cc +++ b/src/DefaultBtProgressInfoFile.cc @@ -52,6 +52,7 @@ #include "a2io.h" #include "DownloadFailureException.h" #include "StringFormat.h" +#include "fmt.h" #include "array_fun.h" #include "DownloadContext.h" #ifdef ENABLE_BITTORRENT @@ -78,12 +79,11 @@ std::string createFilename DefaultBtProgressInfoFile::DefaultBtProgressInfoFile (const SharedHandle<DownloadContext>& dctx, const PieceStorageHandle& pieceStorage, - const Option* option): - dctx_(dctx), - pieceStorage_(pieceStorage), - option_(option), - logger_(LogFactory::getInstance()), - filename_(createFilename(dctx_, getSuffix())) + const Option* option) + : dctx_(dctx), + pieceStorage_(pieceStorage), + option_(option), + filename_(createFilename(dctx_, getSuffix())) {} DefaultBtProgressInfoFile::~DefaultBtProgressInfoFile() {} @@ -105,7 +105,7 @@ bool DefaultBtProgressInfoFile::isTorrentDownload() // Since version 0001, Integers are saved in binary form, network byte order. void DefaultBtProgressInfoFile::save() { - logger_->info(MSG_SAVING_SEGMENT_FILE, filename_.c_str()); + A2_LOG_INFO(fmt(MSG_SAVING_SEGMENT_FILE, filename_.c_str())); std::string filenameTemp = filename_+"__temp"; { std::ofstream o(filenameTemp.c_str(), std::ios::out|std::ios::binary); @@ -201,7 +201,7 @@ void DefaultBtProgressInfoFile::save() throw DL_ABORT_EX (StringFormat(EX_SEGMENT_FILE_WRITE, filename_.c_str()).str()); } - logger_->info(MSG_SAVED_SEGMENT_FILE); + A2_LOG_INFO(MSG_SAVED_SEGMENT_FILE); } if(!File(filenameTemp).renameTo(filename_)) { throw DL_ABORT_EX @@ -225,7 +225,7 @@ void DefaultBtProgressInfoFile::save() // 2) network byte order if version == 0001 void DefaultBtProgressInfoFile::load() { - logger_->info(MSG_LOADING_SEGMENT_FILE, filename_.c_str()); + A2_LOG_INFO(fmt(MSG_LOADING_SEGMENT_FILE, filename_.c_str())); std::ifstream in(filename_.c_str(), std::ios::in|std::ios::binary); if(!in) { throw DL_ABORT_EX @@ -251,9 +251,7 @@ void DefaultBtProgressInfoFile::load() bool infoHashCheckEnabled = false; if(extension[3]&1 && isTorrentDownload()) { infoHashCheckEnabled = true; - if(logger_->debug()) { - logger_->debug("InfoHash checking enabled."); - } + A2_LOG_DEBUG("InfoHash checking enabled."); } uint32_t infoHashLength; @@ -422,7 +420,7 @@ void DefaultBtProgressInfoFile::load() util::convertBitfield(&dest, &src); pieceStorage_->setBitfield(dest.getBitfield(), dest.getBitfieldLength()); } - logger_->info(MSG_LOADED_SEGMENT_FILE); + A2_LOG_INFO(MSG_LOADED_SEGMENT_FILE); } void DefaultBtProgressInfoFile::removeFile() @@ -437,10 +435,10 @@ bool DefaultBtProgressInfoFile::exists() { File f(filename_); if(f.isFile()) { - logger_->info(MSG_SEGMENT_FILE_EXISTS, filename_.c_str()); + A2_LOG_INFO(fmt(MSG_SEGMENT_FILE_EXISTS, filename_.c_str())); return true; } else { - logger_->info(MSG_SEGMENT_FILE_DOES_NOT_EXIST, filename_.c_str()); + A2_LOG_INFO(fmt(MSG_SEGMENT_FILE_DOES_NOT_EXIST, filename_.c_str())); return false; } } diff --git a/src/DefaultBtProgressInfoFile.h b/src/DefaultBtProgressInfoFile.h index 12aedb85..8f10b001 100644 --- a/src/DefaultBtProgressInfoFile.h +++ b/src/DefaultBtProgressInfoFile.h @@ -43,7 +43,6 @@ class DownloadContext; class PieceStorage; class PeerStorage; class BtRuntime; -class Logger; class Option; class DefaultBtProgressInfoFile : public BtProgressInfoFile { @@ -55,7 +54,6 @@ private: SharedHandle<BtRuntime> btRuntime_; #endif // ENABLE_BITTORRENT const Option* option_; - Logger* logger_; std::string filename_; bool isTorrentDownload(); diff --git a/src/DefaultBtRequestFactory.cc b/src/DefaultBtRequestFactory.cc index 070775af..73d39cef 100644 --- a/src/DefaultBtRequestFactory.cc +++ b/src/DefaultBtRequestFactory.cc @@ -47,25 +47,16 @@ #include "a2functional.h" #include "SimpleRandomizer.h" #include "array_fun.h" +#include "fmt.h" namespace aria2 { -DefaultBtRequestFactory::DefaultBtRequestFactory(): - dispatcher_(0), - messageFactory_(0), - logger_(LogFactory::getInstance()) -{ - if(logger_->debug()) { - logger_->debug("DefaultBtRequestFactory::instantiated"); - } -} +DefaultBtRequestFactory::DefaultBtRequestFactory() + : dispatcher_(0), + messageFactory_(0) +{} -DefaultBtRequestFactory::~DefaultBtRequestFactory() -{ - if(logger_->debug()) { - logger_->debug("DefaultBtRequestFactory::deleted"); - } -} +DefaultBtRequestFactory::~DefaultBtRequestFactory() {} void DefaultBtRequestFactory::addTargetPiece(const SharedHandle<Piece>& piece) { @@ -176,14 +167,12 @@ void DefaultBtRequestFactory::createRequestMessages getnum -= blockIndexes.size(); for(std::vector<size_t>::const_iterator i = blockIndexes.begin(), eoi2 = blockIndexes.end(); i != eoi2; ++i) { - if(logger_->debug()) { - logger_->debug - ("Creating RequestMessage index=%lu, begin=%u," - " blockIndex=%lu", - static_cast<unsigned long>(piece->getIndex()), - static_cast<unsigned int>((*i)*piece->getBlockLength()), - static_cast<unsigned long>(*i)); - } + A2_LOG_DEBUG + (fmt("Creating RequestMessage index=%lu, begin=%u," + " blockIndex=%lu", + static_cast<unsigned long>(piece->getIndex()), + static_cast<unsigned int>((*i)*piece->getBlockLength()), + static_cast<unsigned long>(*i))); requests.push_back (messageFactory_->createRequestMessage(piece, *i)); } @@ -222,14 +211,12 @@ void DefaultBtRequestFactory::createRequestMessagesOnEndGame const size_t& blockIndex = *bitr; if(!dispatcher_->isOutstandingRequest(piece->getIndex(), blockIndex)) { - if(logger_->debug()) { - logger_->debug - ("Creating RequestMessage index=%lu, begin=%u," - " blockIndex=%lu", - static_cast<unsigned long>(piece->getIndex()), - static_cast<unsigned int>(blockIndex*piece->getBlockLength()), - static_cast<unsigned long>(blockIndex)); - } + A2_LOG_DEBUG + (fmt("Creating RequestMessage index=%lu, begin=%u," + " blockIndex=%lu", + static_cast<unsigned long>(piece->getIndex()), + static_cast<unsigned int>(blockIndex*piece->getBlockLength()), + static_cast<unsigned long>(blockIndex))); requests.push_back(messageFactory_->createRequestMessage (piece, blockIndex)); } diff --git a/src/DefaultBtRequestFactory.h b/src/DefaultBtRequestFactory.h index 3c2b3492..33016dcb 100644 --- a/src/DefaultBtRequestFactory.h +++ b/src/DefaultBtRequestFactory.h @@ -48,7 +48,6 @@ class Peer; class BtMessageDispatcher; class BtMessageFactory; class Piece; -class Logger; class DefaultBtRequestFactory : public BtRequestFactory { private: @@ -57,7 +56,6 @@ private: BtMessageDispatcher* dispatcher_; BtMessageFactory* messageFactory_; std::deque<SharedHandle<Piece> > pieces_; - Logger* logger_; public: DefaultBtRequestFactory(); diff --git a/src/DefaultExtensionMessageFactory.cc b/src/DefaultExtensionMessageFactory.cc index a49abf2e..a69e1257 100644 --- a/src/DefaultExtensionMessageFactory.cc +++ b/src/DefaultExtensionMessageFactory.cc @@ -37,8 +37,6 @@ #include "DlAbortEx.h" #include "HandshakeExtensionMessage.h" #include "UTPexExtensionMessage.h" -#include "LogFactory.h" -#include "Logger.h" #include "StringFormat.h" #include "PeerStorage.h" #include "ExtensionMessageRegistry.h" @@ -56,18 +54,18 @@ namespace aria2 { -DefaultExtensionMessageFactory::DefaultExtensionMessageFactory(): - messageFactory_(0), - dispatcher_(0), - tracker_(0), - logger_(LogFactory::getInstance()) {} +DefaultExtensionMessageFactory::DefaultExtensionMessageFactory() + : messageFactory_(0), + dispatcher_(0), + tracker_(0) +{} DefaultExtensionMessageFactory::DefaultExtensionMessageFactory (const SharedHandle<Peer>& peer, - const SharedHandle<ExtensionMessageRegistry>& registry): - peer_(peer), - registry_(registry), - logger_(LogFactory::getInstance()) {} + const SharedHandle<ExtensionMessageRegistry>& registry) + : peer_(peer), + registry_(registry) +{} DefaultExtensionMessageFactory::~DefaultExtensionMessageFactory() {} diff --git a/src/DefaultExtensionMessageFactory.h b/src/DefaultExtensionMessageFactory.h index e388b8d9..2ce5d772 100644 --- a/src/DefaultExtensionMessageFactory.h +++ b/src/DefaultExtensionMessageFactory.h @@ -41,7 +41,6 @@ namespace aria2 { class PeerStorage; class Peer; -class Logger; class ExtensionMessageRegistry; class DownloadContext; class BtMessageFactory; @@ -63,9 +62,6 @@ private: BtMessageDispatcher* dispatcher_; UTMetadataRequestTracker* tracker_; - - Logger* logger_; - public: DefaultExtensionMessageFactory(); diff --git a/src/DefaultPeerStorage.cc b/src/DefaultPeerStorage.cc index 95c02527..ac390acb 100644 --- a/src/DefaultPeerStorage.cc +++ b/src/DefaultPeerStorage.cc @@ -46,6 +46,7 @@ #include "PieceStorage.h" #include "wallclock.h" #include "a2functional.h" +#include "fmt.h" namespace aria2 { @@ -53,13 +54,12 @@ namespace { const int MAX_PEER_LIST_SIZE = 1024; } // namespace -DefaultPeerStorage::DefaultPeerStorage(): - logger_(LogFactory::getInstance()), - removedPeerSessionDownloadLength_(0), - removedPeerSessionUploadLength_(0), - seederStateChoke_(new BtSeederStateChoke()), - leecherStateChoke_(new BtLeecherStateChoke()), - lastTransferStatMapUpdated_(0) +DefaultPeerStorage::DefaultPeerStorage() + : removedPeerSessionDownloadLength_(0), + removedPeerSessionUploadLength_(0), + seederStateChoke_(new BtSeederStateChoke()), + leecherStateChoke_(new BtLeecherStateChoke()), + lastTransferStatMapUpdated_(0) {} DefaultPeerStorage::~DefaultPeerStorage() @@ -103,10 +103,9 @@ size_t calculateMaxPeerListSize(const SharedHandle<BtRuntime>& btRuntime) bool DefaultPeerStorage::addPeer(const SharedHandle<Peer>& peer) { if(isPeerAlreadyAdded(peer)) { - if(logger_->debug()) { - logger_->debug("Adding %s:%u is rejected because it has been already" - " added.", peer->getIPAddress().c_str(), peer->getPort()); - } + A2_LOG_DEBUG(fmt("Adding %s:%u is rejected because it has been already" + " added.", + peer->getIPAddress().c_str(), peer->getPort())); return false; } size_t maxPeerListSize = calculateMaxPeerListSize(btRuntime_); @@ -123,10 +122,8 @@ void DefaultPeerStorage::addPeer(const std::vector<SharedHandle<Peer> >& peers) eoi = peers.end(); itr != eoi; ++itr) { const SharedHandle<Peer>& peer = *itr; if(addPeer(peer)) { - if(logger_->debug()) { - logger_->debug(MSG_ADDING_PEER, - peer->getIPAddress().c_str(), peer->getPort()); - } + A2_LOG_DEBUG(fmt(MSG_ADDING_PEER, + peer->getIPAddress().c_str(), peer->getPort())); } } } @@ -241,9 +238,7 @@ TransferStat DefaultPeerStorage::calculateStat() { TransferStat stat; if(lastTransferStatMapUpdated_.differenceInMillis(global::wallclock) >= 250) { - if(logger_->debug()) { - logger_->debug("Updating TransferStat of PeerStorage"); - } + A2_LOG_DEBUG("Updating TransferStat of PeerStorage"); lastTransferStatMapUpdated_ = global::wallclock; peerTransferStatMap_.clear(); std::vector<SharedHandle<Peer> > activePeers; @@ -272,9 +267,7 @@ TransferStat DefaultPeerStorage::calculateStat() void DefaultPeerStorage::updateTransferStatFor(const SharedHandle<Peer>& peer) { - if(logger_->debug()) { - logger_->debug("Updating TransferStat for peer %s", peer->getID().c_str()); - } + A2_LOG_DEBUG(fmt("Updating TransferStat for peer %s", peer->getID().c_str())); std::map<std::string, TransferStat>::iterator itr = peerTransferStatMap_.find(peer->getID()); if(itr == peerTransferStatMap_.end()) { @@ -340,10 +333,8 @@ void DefaultPeerStorage::returnPeer(const SharedHandle<Peer>& peer) std::deque<SharedHandle<Peer> >::iterator itr = std::find_if(peers_.begin(), peers_.end(), derefEqual(peer)); if(itr == peers_.end()) { - if(logger_->debug()) { - logger_->debug("Cannot find peer %s:%u in PeerStorage.", - peer->getIPAddress().c_str(), peer->getPort()); - } + A2_LOG_DEBUG(fmt("Cannot find peer %s:%u in PeerStorage.", + peer->getIPAddress().c_str(), peer->getPort())); } else { peers_.erase(itr); diff --git a/src/DefaultPeerStorage.h b/src/DefaultPeerStorage.h index fc62c58a..bbcf2966 100644 --- a/src/DefaultPeerStorage.h +++ b/src/DefaultPeerStorage.h @@ -43,7 +43,6 @@ namespace aria2 { -class Logger; class BtRuntime; class BtSeederStateChoke; class BtLeecherStateChoke; @@ -55,7 +54,6 @@ private: SharedHandle<PieceStorage> pieceStorage_; std::deque<SharedHandle<Peer> > peers_; std::deque<SharedHandle<Peer> > droppedPeers_; - Logger* logger_; uint64_t removedPeerSessionDownloadLength_; uint64_t removedPeerSessionUploadLength_; diff --git a/src/DefaultPieceStorage.cc b/src/DefaultPieceStorage.cc index 10746f1a..72a79140 100644 --- a/src/DefaultPieceStorage.cc +++ b/src/DefaultPieceStorage.cc @@ -55,6 +55,7 @@ #include "a2functional.h" #include "Option.h" #include "StringFormat.h" +#include "fmt.h" #include "RarestPieceSelector.h" #include "array_fun.h" #include "PieceStatMan.h" @@ -67,20 +68,20 @@ namespace aria2 { DefaultPieceStorage::DefaultPieceStorage -(const SharedHandle<DownloadContext>& downloadContext, const Option* option): - downloadContext_(downloadContext), - bitfieldMan_(new BitfieldMan(downloadContext->getPieceLength(), - downloadContext->getTotalLength())), - diskWriterFactory_(new DefaultDiskWriterFactory()), - endGame_(false), - endGamePieceNum_(END_GAME_PIECE_NUM), - logger_(LogFactory::getInstance()), - option_(option), - pieceStatMan_(new PieceStatMan(downloadContext->getNumPieces(), true)), - pieceSelector_(new RarestPieceSelector(pieceStatMan_)) +(const SharedHandle<DownloadContext>& downloadContext, const Option* option) + : downloadContext_(downloadContext), + bitfieldMan_(new BitfieldMan(downloadContext->getPieceLength(), + downloadContext->getTotalLength())), + diskWriterFactory_(new DefaultDiskWriterFactory()), + endGame_(false), + endGamePieceNum_(END_GAME_PIECE_NUM), + option_(option), + pieceStatMan_(new PieceStatMan(downloadContext->getNumPieces(), true)), + pieceSelector_(new RarestPieceSelector(pieceStatMan_)) {} -DefaultPieceStorage::~DefaultPieceStorage() { +DefaultPieceStorage::~DefaultPieceStorage() +{ delete bitfieldMan_; } @@ -130,10 +131,8 @@ void DefaultPieceStorage::addUsedPiece(const SharedHandle<Piece>& piece) std::lower_bound(usedPieces_.begin(), usedPieces_.end(), piece, DerefLess<SharedHandle<Piece> >()); usedPieces_.insert(i, piece); - if(logger_->debug()) { - logger_->debug("usedPieces_.size()=%lu", - static_cast<unsigned long>(usedPieces_.size())); - } + A2_LOG_DEBUG(fmt("usedPieces_.size()=%lu", + static_cast<unsigned long>(usedPieces_.size()))); } SharedHandle<Piece> DefaultPieceStorage::findUsedPiece(size_t index) const @@ -428,12 +427,12 @@ void DefaultPieceStorage::completePiece(const SharedHandle<Piece>& piece) if(downloadFinished()) { downloadContext_->resetDownloadStopTime(); if(isSelectiveDownloadingMode()) { - logger_->notice(MSG_SELECTIVE_DOWNLOAD_COMPLETED); + A2_LOG_NOTICE(MSG_SELECTIVE_DOWNLOAD_COMPLETED); // following line was commented out in order to stop sending request // message after user-specified files were downloaded. //finishSelectiveDownloadingMode(); } else { - logger_->info(MSG_DOWNLOAD_COMPLETED); + A2_LOG_INFO(MSG_DOWNLOAD_COMPLETED); } #ifdef ENABLE_BITTORRENT if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) { @@ -561,9 +560,7 @@ bool DefaultPieceStorage::allDownloadFinished() void DefaultPieceStorage::initStorage() { if(downloadContext_->getFileEntries().size() == 1) { - if(logger_->debug()) { - logger_->debug("Instantiating DirectDiskAdaptor"); - } + A2_LOG_DEBUG("Instantiating DirectDiskAdaptor"); DirectDiskAdaptorHandle directDiskAdaptor(new DirectDiskAdaptor()); directDiskAdaptor->setTotalLength(downloadContext_->getTotalLength()); directDiskAdaptor->setFileEntries @@ -579,9 +576,7 @@ void DefaultPieceStorage::initStorage() directDiskAdaptor->setDiskWriter(writer); diskAdaptor_ = directDiskAdaptor; } else { - if(logger_->debug()) { - logger_->debug("Instantiating MultiDiskAdaptor"); - } + A2_LOG_DEBUG("Instantiating MultiDiskAdaptor"); MultiDiskAdaptorHandle multiDiskAdaptor(new MultiDiskAdaptor()); multiDiskAdaptor->setFileEntries(downloadContext_->getFileEntries().begin(), downloadContext_->getFileEntries().end()); @@ -671,10 +666,8 @@ void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed) std::deque<HaveEntry>::iterator itr = std::find_if(haves_.begin(), haves_.end(), FindElapsedHave(elapsed)); if(itr != haves_.end()) { - if(logger_->debug()) { - logger_->debug(MSG_REMOVED_HAVE_ENTRY, - static_cast<unsigned long>(haves_.end()-itr)); - } + A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY, + static_cast<unsigned long>(haves_.end()-itr))); haves_.erase(itr, haves_.end()); } } diff --git a/src/DefaultPieceStorage.h b/src/DefaultPieceStorage.h index bde118a3..0fb22ff3 100644 --- a/src/DefaultPieceStorage.h +++ b/src/DefaultPieceStorage.h @@ -43,7 +43,6 @@ namespace aria2 { class DownloadContext; class BitfieldMan; -class Logger; class Option; class DiskWriterFactory; class FileEntry; @@ -80,7 +79,6 @@ private: bool endGame_; size_t endGamePieceNum_; - Logger* logger_; const Option* option_; std::deque<HaveEntry> haves_; diff --git a/src/DiskAdaptor.cc b/src/DiskAdaptor.cc index 8d307869..12b42f66 100644 --- a/src/DiskAdaptor.cc +++ b/src/DiskAdaptor.cc @@ -34,14 +34,12 @@ /* copyright --> */ #include "DiskAdaptor.h" #include "FileEntry.h" -#include "LogFactory.h" -#include "Logger.h" namespace aria2 { -DiskAdaptor::DiskAdaptor(): - fallocate_(false), - logger_(LogFactory::getInstance()) {} +DiskAdaptor::DiskAdaptor() + : fallocate_(false) +{} DiskAdaptor::~DiskAdaptor() {} diff --git a/src/DiskAdaptor.h b/src/DiskAdaptor.h index fa215707..91bc13b0 100644 --- a/src/DiskAdaptor.h +++ b/src/DiskAdaptor.h @@ -45,7 +45,6 @@ namespace aria2 { class FileEntry; -class Logger; class FileAllocationIterator; class DiskAdaptor:public BinaryStream { @@ -53,13 +52,6 @@ private: std::vector<SharedHandle<FileEntry> > fileEntries_; bool fallocate_; - - Logger* logger_; -protected: - Logger* getLogger() const - { - return logger_; - } public: DiskAdaptor(); virtual ~DiskAdaptor(); diff --git a/src/DownloadCommand.cc b/src/DownloadCommand.cc index b47f6d28..837ee004 100644 --- a/src/DownloadCommand.cc +++ b/src/DownloadCommand.cc @@ -45,6 +45,7 @@ #include "SegmentMan.h" #include "Segment.h" #include "Logger.h" +#include "LogFactory.h" #include "ChecksumCheckIntegrityEntry.h" #include "PieceStorage.h" #include "CheckIntegrityCommand.h" @@ -56,6 +57,7 @@ #include "message.h" #include "prefs.h" #include "StringFormat.h" +#include "fmt.h" #include "RequestGroupMan.h" #include "wallclock.h" #include "SinkStreamFilter.h" @@ -197,10 +199,8 @@ bool DownloadCommand::executeInternal() { // If segment->getLength() == 0, the server doesn't provide // content length, but the client detected that download // completed. - if(getLogger()->info()) { - getLogger()->info(MSG_SEGMENT_DOWNLOAD_COMPLETED, - util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt(MSG_SEGMENT_DOWNLOAD_COMPLETED, + util::itos(getCuid()).c_str())); #ifdef ENABLE_MESSAGE_DIGEST { @@ -213,11 +213,8 @@ bool DownloadCommand::executeInternal() { !getDownloadContext()->hasAttribute(bittorrent::BITTORRENT)) && #endif // ENABLE_BITTORRENT segment->isHashCalculated()) { - if(getLogger()->debug()) { - getLogger()->debug - ("Hash is available! index=%lu", - static_cast<unsigned long>(segment->getIndex())); - } + A2_LOG_DEBUG(fmt("Hash is available! index=%lu", + static_cast<unsigned long>(segment->getIndex()))); validatePieceHash (segment, expectedPieceHash, segment->getHashString()); } else { @@ -340,14 +337,14 @@ void DownloadCommand::validatePieceHash(const SharedHandle<Segment>& segment, const std::string& actualPieceHash) { if(actualPieceHash == expectedPieceHash) { - getLogger()->info(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str()); + A2_LOG_INFO(fmt(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str())); getSegmentMan()->completeSegment(getCuid(), segment); } else { - getLogger()->info(EX_INVALID_CHUNK_CHECKSUM, - static_cast<unsigned long>(segment->getIndex()), - util::itos(segment->getPosition(), true).c_str(), - expectedPieceHash.c_str(), - actualPieceHash.c_str()); + A2_LOG_INFO(fmt(EX_INVALID_CHUNK_CHECKSUM, + static_cast<unsigned long>(segment->getIndex()), + util::itos(segment->getPosition(), true).c_str(), + expectedPieceHash.c_str(), + actualPieceHash.c_str())); segment->clear(); getSegmentMan()->cancelSegment(getCuid()); throw DL_RETRY_EX diff --git a/src/DownloadEngine.cc b/src/DownloadEngine.cc index a6b33732..ec23ce2a 100644 --- a/src/DownloadEngine.cc +++ b/src/DownloadEngine.cc @@ -64,6 +64,7 @@ #include "CheckIntegrityEntry.h" #include "BtProgressInfoFile.h" #include "DownloadContext.h" +#include "fmt.h" #ifdef ENABLE_BITTORRENT # include "BtRegistry.h" #endif // ENABLE_BITTORRENT @@ -85,17 +86,16 @@ volatile sig_atomic_t globalHaltRequested = 0; } // namespace global -DownloadEngine::DownloadEngine(const SharedHandle<EventPoll>& eventPoll): - eventPoll_(eventPoll), - logger_(LogFactory::getInstance()), - haltRequested_(false), - noWait_(false), - refreshInterval_(DEFAULT_REFRESH_INTERVAL), - cookieStorage_(new CookieStorage()), +DownloadEngine::DownloadEngine(const SharedHandle<EventPoll>& eventPoll) + : eventPoll_(eventPoll), + haltRequested_(false), + noWait_(false), + refreshInterval_(DEFAULT_REFRESH_INTERVAL), + cookieStorage_(new CookieStorage()), #ifdef ENABLE_BITTORRENT - btRegistry_(new BtRegistry()), + btRegistry_(new BtRegistry()), #endif // ENABLE_BITTORRENT - dnsCache_(new DNSCache()) + dnsCache_(new DNSCache()) { unsigned char sessionId[20]; util::generateRandomKey(sessionId); @@ -217,14 +217,14 @@ void DownloadEngine::afterEachIteration() { requestGroupMan_->calculateStat(); if(global::globalHaltRequested == 1) { - logger_->notice(_("Shutdown sequence commencing..." - " Press Ctrl-C again for emergency shutdown.")); + A2_LOG_NOTICE(_("Shutdown sequence commencing..." + " Press Ctrl-C again for emergency shutdown.")); requestHalt(); global::globalHaltRequested = 2; setNoWait(true); setRefreshInterval(0); } else if(global::globalHaltRequested == 3) { - logger_->notice(_("Emergency shutdown sequence commencing...")); + A2_LOG_NOTICE(_("Emergency shutdown sequence commencing...")); requestForceHalt(); global::globalHaltRequested = 4; setNoWait(true); @@ -276,15 +276,13 @@ void DownloadEngine::addRoutineCommand(Command* command) void DownloadEngine::poolSocket(const std::string& key, const SocketPoolEntry& entry) { - logger_->info("Pool socket for %s", key.c_str()); + A2_LOG_INFO(fmt("Pool socket for %s", key.c_str())); std::multimap<std::string, SocketPoolEntry>::value_type p(key, entry); socketPool_.insert(p); if(lastSocketPoolScan_.difference(global::wallclock) >= 60) { std::multimap<std::string, SocketPoolEntry> newPool; - if(logger_->debug()) { - logger_->debug("Scaning SocketPool and erasing timed out entry."); - } + A2_LOG_DEBUG("Scaning SocketPool and erasing timed out entry."); lastSocketPoolScan_ = global::wallclock; for(std::multimap<std::string, SocketPoolEntry>::iterator i = socketPool_.begin(), eoi = socketPool_.end(); i != eoi; ++i) { @@ -292,11 +290,9 @@ void DownloadEngine::poolSocket(const std::string& key, newPool.insert(*i); } } - if(logger_->debug()) { - logger_->debug - ("%lu entries removed.", - static_cast<unsigned long>(socketPool_.size()-newPool.size())); - } + A2_LOG_DEBUG(fmt("%lu entries removed.", + static_cast<unsigned long> + (socketPool_.size()-newPool.size()))); socketPool_ = newPool; } } @@ -402,7 +398,7 @@ DownloadEngine::findSocketPoolEntry(const std::string& key) // We assume that if socket is readable it means peer shutdowns // connection and the socket will receive EOF. So skip it. if(!e.isTimeout() && !e.getSocket()->isReadable(0)) { - logger_->info("Found socket for %s", key.c_str()); + A2_LOG_INFO(fmt("Found socket for %s", key.c_str())); return i; } } diff --git a/src/DownloadEngine.h b/src/DownloadEngine.h index ded45806..675920cb 100644 --- a/src/DownloadEngine.h +++ b/src/DownloadEngine.h @@ -56,7 +56,6 @@ namespace aria2 { -class Logger; class Option; class RequestGroupMan; class StatCalc; @@ -78,8 +77,6 @@ private: SharedHandle<EventPoll> eventPoll_; - Logger* logger_; - SharedHandle<StatCalc> statCalc_; bool haltRequested_; diff --git a/src/DownloadEngineFactory.cc b/src/DownloadEngineFactory.cc index 0f4b0d18..5b793cad 100644 --- a/src/DownloadEngineFactory.cc +++ b/src/DownloadEngineFactory.cc @@ -36,8 +36,6 @@ #include <algorithm> -#include "LogFactory.h" -#include "Logger.h" #include "Option.h" #include "RequestGroup.h" #include "DownloadEngine.h" @@ -80,8 +78,7 @@ namespace aria2 { -DownloadEngineFactory::DownloadEngineFactory(): - logger_(LogFactory::getInstance()) {} +DownloadEngineFactory::DownloadEngineFactory() {} DownloadEngineHandle DownloadEngineFactory::newDownloadEngine diff --git a/src/DownloadEngineFactory.h b/src/DownloadEngineFactory.h index 23311842..1d42a252 100644 --- a/src/DownloadEngineFactory.h +++ b/src/DownloadEngineFactory.h @@ -43,14 +43,11 @@ namespace aria2 { -class Logger; class Option; class RequestGroup; class DownloadEngine; class DownloadEngineFactory { -private: - Logger* logger_; public: DownloadEngineFactory(); diff --git a/src/DownloadHandler.cc b/src/DownloadHandler.cc index b708e2c1..db2c02fe 100644 --- a/src/DownloadHandler.cc +++ b/src/DownloadHandler.cc @@ -33,15 +33,13 @@ */ /* copyright --> */ #include "DownloadHandler.h" -#include "LogFactory.h" -#include "Logger.h" #include "RequestGroup.h" #include "RequestGroupCriteria.h" #include "DownloadContext.h" namespace aria2 { -DownloadHandler::DownloadHandler():logger_(LogFactory::getInstance()) {} +DownloadHandler::DownloadHandler() {} DownloadHandler::~DownloadHandler() {} diff --git a/src/DownloadHandler.h b/src/DownloadHandler.h index 15daba79..a042eec7 100644 --- a/src/DownloadHandler.h +++ b/src/DownloadHandler.h @@ -44,20 +44,12 @@ namespace aria2 { class RequestGroup; -class Logger; class RequestGroupCriteria; class DownloadHandler { private: SharedHandle<RequestGroupCriteria> criteria_; - - Logger* logger_; -protected: - Logger* getLogger() const - { - return logger_; - } public: DownloadHandler(); diff --git a/src/EpollEventPoll.cc b/src/EpollEventPoll.cc index d7077fdb..e82b051c 100644 --- a/src/EpollEventPoll.cc +++ b/src/EpollEventPoll.cc @@ -44,6 +44,7 @@ #include "Logger.h" #include "util.h" #include "a2functional.h" +#include "fmt.h" namespace aria2 { @@ -80,10 +81,9 @@ struct epoll_event EpollEventPoll::KSocketEntry::getEvents() return epEvent; } -EpollEventPoll::EpollEventPoll(): - epEventsSize_(EPOLL_EVENTS_MAX), - epEvents_(new struct epoll_event[epEventsSize_]), - logger_(LogFactory::getInstance()) +EpollEventPoll::EpollEventPoll() + : epEventsSize_(EPOLL_EVENTS_MAX), + epEvents_(new struct epoll_event[epEventsSize_]) { epfd_ = epoll_create(EPOLL_EVENTS_MAX); } @@ -95,9 +95,10 @@ EpollEventPoll::~EpollEventPoll() while((r = close(epfd_)) == -1 && errno == EINTR); int errNum = errno; if(r == -1) { - logger_->error("Error occurred while closing epoll file descriptor" - " %d: %s", - epfd_, util::safeStrerror(errNum).c_str()); + A2_LOG_ERROR(fmt("Error occurred while closing epoll file descriptor" + " %d: %s", + epfd_, + util::safeStrerror(errNum).c_str())); } } delete [] epEvents_; @@ -201,10 +202,9 @@ bool EpollEventPoll::addEvents(sock_t socket, errNum = errno; } if(r == -1) { - if(logger_->debug()) { - logger_->debug("Failed to add socket event %d:%s", - socket, util::safeStrerror(errNum).c_str()); - } + A2_LOG_DEBUG(fmt("Failed to add socket event %d:%s", + socket, + util::safeStrerror(errNum).c_str())); return false; } else { return true; @@ -253,25 +253,19 @@ bool EpollEventPoll::deleteEvents(sock_t socket, r = epoll_ctl(epfd_, EPOLL_CTL_MOD, (*i)->getSocket(), &epEvent); errNum = r; if(r == -1) { - if(logger_->debug()) { - logger_->debug("Failed to delete socket event, but may be ignored:%s", - util::safeStrerror(errNum).c_str()); - } + A2_LOG_DEBUG(fmt("Failed to delete socket event, but may be ignored:%s", + util::safeStrerror(errNum).c_str())); } } if(r == -1) { - if(logger_->debug()) { - logger_->debug("Failed to delete socket event:%s", - util::safeStrerror(errNum).c_str()); - } + A2_LOG_DEBUG(fmt("Failed to delete socket event:%s", + util::safeStrerror(errNum).c_str())); return false; } else { return true; } } else { - if(logger_->debug()) { - logger_->debug("Socket %d is not found in SocketEntries.", socket); - } + A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket)); return false; } } diff --git a/src/EpollEventPoll.h b/src/EpollEventPoll.h index 144319b9..8b6ba167 100644 --- a/src/EpollEventPoll.h +++ b/src/EpollEventPoll.h @@ -48,8 +48,6 @@ namespace aria2 { -class Logger; - class EpollEventPoll : public EventPoll { private: class KSocketEntry; @@ -84,8 +82,6 @@ private: static const size_t EPOLL_EVENTS_MAX = 1024; - Logger* logger_; - bool addEvents(sock_t socket, const KEvent& event); bool deleteEvents(sock_t socket, const KEvent& event); diff --git a/src/FeedbackURISelector.cc b/src/FeedbackURISelector.cc index 6ee7d9d2..cb9ad199 100644 --- a/src/FeedbackURISelector.cc +++ b/src/FeedbackURISelector.cc @@ -45,13 +45,14 @@ #include "LogFactory.h" #include "a2algo.h" #include "uri.h" +#include "fmt.h" namespace aria2 { FeedbackURISelector::FeedbackURISelector -(const SharedHandle<ServerStatMan>& serverStatMan): - serverStatMan_(serverStatMan), - logger_(LogFactory::getInstance()) {} +(const SharedHandle<ServerStatMan>& serverStatMan) + : serverStatMan_(serverStatMan) +{} FeedbackURISelector::~FeedbackURISelector() {} @@ -71,12 +72,12 @@ std::string FeedbackURISelector::select (FileEntry* fileEntry, const std::vector<std::pair<size_t, std::string> >& usedHosts) { - if(logger_->debug()) { + if(A2_LOG_DEBUG_ENABLED) { for(std::vector<std::pair<size_t, std::string> >::const_iterator i = usedHosts.begin(), eoi = usedHosts.end(); i != eoi; ++i) { - logger_->debug("UsedHost=%lu, %s", - static_cast<unsigned long>((*i).first), - (*i).second.c_str()); + A2_LOG_DEBUG(fmt("UsedHost=%lu, %s", + static_cast<unsigned long>((*i).first), + (*i).second.c_str())); } } if(fileEntry->getRemainingUris().empty()) { @@ -86,18 +87,14 @@ std::string FeedbackURISelector::select // it again without usedHosts. std::string uri = selectFaster(fileEntry->getRemainingUris(), usedHosts); if(uri.empty()) { - if(logger_->debug()) { - logger_->debug("No URI returned from selectFaster()"); - } + A2_LOG_DEBUG("No URI returned from selectFaster()"); uri = selectRarer(fileEntry->getRemainingUris(), usedHosts); } if(!uri.empty()) { std::deque<std::string>& uris = fileEntry->getRemainingUris(); uris.erase(std::find(uris.begin(), uris.end(), uri)); } - if(logger_->debug()) { - logger_->debug("FeedbackURISelector selected %s", uri.c_str()); - } + A2_LOG_DEBUG(fmt("FeedbackURISelector selected %s", uri.c_str())); return uri; } @@ -116,9 +113,7 @@ std::string FeedbackURISelector::selectRarer SharedHandle<ServerStat> ss = serverStatMan_->find(us.host, us.protocol); if(ss && ss->isError()) { - if(logger_->debug()) { - logger_->debug("Error not considered: %s", (*i).c_str()); - } + A2_LOG_DEBUG(fmt("Error not considered: %s", (*i).c_str())); continue; } cands.push_back(std::make_pair(us.host, *i)); @@ -154,9 +149,7 @@ std::string FeedbackURISelector::selectFaster } if(findSecond(usedHosts.begin(), usedHosts.end(), us.host) != usedHosts.end()) { - if(logger_->debug()) { - logger_->debug("%s is in usedHosts, not considered", (*i).c_str()); - } + A2_LOG_DEBUG(fmt("%s is in usedHosts, not considered", (*i).c_str())); continue; } SharedHandle<ServerStat> ss = @@ -175,15 +168,11 @@ std::string FeedbackURISelector::selectFaster if(normCands.empty()) { return A2STR::NIL; } else { - if(logger_->debug()) { - logger_->debug("Selected from normCands"); - } + A2_LOG_DEBUG("Selected from normCands"); return normCands.front(); } } else { - if(logger_->debug()) { - logger_->debug("Selected from fastCands"); - } + A2_LOG_DEBUG("Selected from fastCands"); std::sort(fastCands.begin(), fastCands.end(), ServerStatFaster()); return fastCands.front().second; } diff --git a/src/FeedbackURISelector.h b/src/FeedbackURISelector.h index cfaddc87..6f5ced64 100644 --- a/src/FeedbackURISelector.h +++ b/src/FeedbackURISelector.h @@ -40,14 +40,11 @@ namespace aria2 { class ServerStatMan; -class Logger; class FeedbackURISelector:public URISelector { private: SharedHandle<ServerStatMan> serverStatMan_; - Logger* logger_; - std::string selectRarer (const std::deque<std::string>& uris, const std::vector<std::pair<size_t, std::string> >& usedHosts); diff --git a/src/FileAllocationCommand.cc b/src/FileAllocationCommand.cc index a0b9a296..3373d784 100644 --- a/src/FileAllocationCommand.cc +++ b/src/FileAllocationCommand.cc @@ -38,6 +38,7 @@ #include "DownloadEngine.h" #include "RequestGroup.h" #include "Logger.h" +#include "LogFactory.h" #include "message.h" #include "prefs.h" #include "util.h" @@ -47,6 +48,7 @@ #include "RecoverableException.h" #include "wallclock.h" #include "RequestGroupMan.h" +#include "fmt.h" namespace aria2 { @@ -66,12 +68,10 @@ bool FileAllocationCommand::executeInternal() } fileAllocationEntry_->allocateChunk(); if(fileAllocationEntry_->finished()) { - if(getLogger()->debug()) { - getLogger()->debug - (MSG_ALLOCATION_COMPLETED, - static_cast<long int>(timer_.difference(global::wallclock)), - util::itos(getRequestGroup()->getTotalLength(), true).c_str()); - } + A2_LOG_DEBUG + (fmt(MSG_ALLOCATION_COMPLETED, + static_cast<long int>(timer_.difference(global::wallclock)), + util::itos(getRequestGroup()->getTotalLength(), true).c_str())); getDownloadEngine()->getFileAllocationMan()->dropPickedEntry(); std::vector<Command*>* commands = new std::vector<Command*>(); @@ -90,11 +90,13 @@ bool FileAllocationCommand::executeInternal() bool FileAllocationCommand::handleException(Exception& e) { getDownloadEngine()->getFileAllocationMan()->dropPickedEntry(); - getLogger()->error - (MSG_FILE_ALLOCATION_FAILURE, e, util::itos(getCuid()).c_str()); - getLogger()->error - (MSG_DOWNLOAD_NOT_COMPLETE, util::itos(getCuid()).c_str(), - getRequestGroup()->getDownloadContext()->getBasePath().c_str()); + A2_LOG_ERROR_EX(fmt(MSG_FILE_ALLOCATION_FAILURE, + util::itos(getCuid()).c_str()), + e); + A2_LOG_ERROR + (fmt(MSG_DOWNLOAD_NOT_COMPLETE, + util::itos(getCuid()).c_str(), + getRequestGroup()->getDownloadContext()->getBasePath().c_str())); return true; } diff --git a/src/FileAllocationDispatcherCommand.cc b/src/FileAllocationDispatcherCommand.cc index 46c2f7fd..58a82061 100644 --- a/src/FileAllocationDispatcherCommand.cc +++ b/src/FileAllocationDispatcherCommand.cc @@ -37,7 +37,9 @@ #include "FileAllocationCommand.h" #include "message.h" #include "Logger.h" +#include "LogFactory.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -51,10 +53,7 @@ Command* FileAllocationDispatcherCommand::createCommand (const SharedHandle<FileAllocationEntry>& entry) { cuid_t newCUID = getDownloadEngine()->newCUID(); - if(getLogger()->info()) { - getLogger()->info(MSG_FILE_ALLOCATION_DISPATCH, - util::itos(newCUID).c_str()); - } + A2_LOG_INFO(fmt(MSG_FILE_ALLOCATION_DISPATCH, util::itos(newCUID).c_str())); FileAllocationCommand* command = new FileAllocationCommand(newCUID, entry->getRequestGroup(), getDownloadEngine(), entry); diff --git a/src/FileEntry.cc b/src/FileEntry.cc index c8664941..59c74fc5 100644 --- a/src/FileEntry.cc +++ b/src/FileEntry.cc @@ -39,31 +39,38 @@ #include "util.h" #include "URISelector.h" +#include "Logger.h" #include "LogFactory.h" #include "wallclock.h" #include "a2algo.h" #include "uri.h" #include "PeerStat.h" +#include "fmt.h" namespace aria2 { -FileEntry::FileEntry(const std::string& path, - uint64_t length, - off_t offset, - const std::vector<std::string>& uris): - path_(path), uris_(uris.begin(), uris.end()), length_(length), - offset_(offset), - requested_(true), - uniqueProtocol_(false), - maxConnectionPerServer_(1), - lastFasterReplace_(0), - logger_(LogFactory::getInstance()) {} - -FileEntry::FileEntry(): - length_(0), offset_(0), requested_(false), - uniqueProtocol_(false), - maxConnectionPerServer_(1), - logger_(LogFactory::getInstance()) {} +FileEntry::FileEntry +(const std::string& path, + uint64_t length, + off_t offset, + const std::vector<std::string>& uris) + : path_(path), + uris_(uris.begin(), uris.end()), + length_(length), + offset_(offset), + requested_(true), + uniqueProtocol_(false), + maxConnectionPerServer_(1), + lastFasterReplace_(0) +{} + +FileEntry::FileEntry() + : length_(0), + offset_(0), + requested_(false), + uniqueProtocol_(false), + maxConnectionPerServer_(1) +{} FileEntry::~FileEntry() {} @@ -172,9 +179,7 @@ FileEntry::getRequest req = requestPool_.front(); requestPool_.pop_front(); inFlightRequests_.push_back(req); - if(logger_->debug()) { - logger_->debug("Picked up from pool: %s", req->getUri().c_str()); - } + A2_LOG_DEBUG(fmt("Picked up from pool: %s", req->getUri().c_str())); } return req; } @@ -273,11 +278,9 @@ void FileEntry::removeURIWhoseHostnameIs(const std::string& hostname) newURIs.push_back(*itr); } } - if(logger_->debug()) { - logger_->debug("Removed %lu duplicate hostname URIs for path=%s", + A2_LOG_DEBUG(fmt("Removed %lu duplicate hostname URIs for path=%s", static_cast<unsigned long>(uris_.size()-newURIs.size()), - getPath().c_str()); - } + getPath().c_str())); uris_.swap(newURIs); } @@ -317,10 +320,10 @@ void FileEntry::extractURIResult void FileEntry::reuseUri(const std::vector<std::string>& ignore) { - if(logger_->debug()) { + if(A2_LOG_DEBUG_ENABLED) { for(std::vector<std::string>::const_iterator i = ignore.begin(), eoi = ignore.end(); i != eoi; ++i) { - logger_->debug("ignore host=%s", (*i).c_str()); + A2_LOG_DEBUG(fmt("ignore host=%s", (*i).c_str())); } } std::deque<std::string> uris = spentUris_; @@ -333,10 +336,10 @@ void FileEntry::reuseUri(const std::vector<std::string>& ignore) std::sort(errorUris.begin(), errorUris.end()); errorUris.erase(std::unique(errorUris.begin(), errorUris.end()), errorUris.end()); - if(logger_->debug()) { + if(A2_LOG_DEBUG_ENABLED) { for(std::vector<std::string>::const_iterator i = errorUris.begin(), eoi = errorUris.end(); i != eoi; ++i) { - logger_->debug("error URI=%s", (*i).c_str()); + A2_LOG_DEBUG(fmt("error URI=%s", (*i).c_str())); } } std::vector<std::string> reusableURIs; @@ -357,11 +360,12 @@ void FileEntry::reuseUri(const std::vector<std::string>& ignore) } reusableURIs.erase(insertionPoint, reusableURIs.end()); size_t ininum = reusableURIs.size(); - if(logger_->debug()) { - logger_->debug("Found %u reusable URIs", static_cast<unsigned int>(ininum)); + if(A2_LOG_DEBUG_ENABLED) { + A2_LOG_DEBUG(fmt("Found %u reusable URIs", + static_cast<unsigned int>(ininum))); for(std::vector<std::string>::const_iterator i = reusableURIs.begin(), eoi = reusableURIs.end(); i != eoi; ++i) { - logger_->debug("URI=%s", (*i).c_str()); + A2_LOG_DEBUG(fmt("URI=%s", (*i).c_str())); } } uris_.insert(uris_.end(), reusableURIs.begin(), reusableURIs.end()); diff --git a/src/FileEntry.h b/src/FileEntry.h index 0d661af3..3fa6444d 100644 --- a/src/FileEntry.h +++ b/src/FileEntry.h @@ -54,8 +54,6 @@ namespace aria2 { class URISelector; -class Logger; - class FileEntry { private: std::string path_; @@ -74,7 +72,6 @@ private: size_t maxConnectionPerServer_; std::string originalName_; Timer lastFasterReplace_; - Logger* logger_; void storePool(const SharedHandle<Request>& request); public: diff --git a/src/FillRequestGroupCommand.cc b/src/FillRequestGroupCommand.cc index 191b153e..5942489c 100644 --- a/src/FillRequestGroupCommand.cc +++ b/src/FillRequestGroupCommand.cc @@ -39,7 +39,9 @@ #include "RecoverableException.h" #include "message.h" #include "Logger.h" +#include "LogFactory.h" #include "DownloadContext.h" +#include "fmt.h" namespace aria2 { @@ -68,7 +70,7 @@ bool FillRequestGroupCommand::execute() rgman->clearQueueCheck(); rgman->fillRequestGroupFromReserver(e_); } catch(RecoverableException& ex) { - getLogger()->error(EX_EXCEPTION_CAUGHT, ex); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex); // Re-request queue check to fulfill the requests of all // downloads, some might come after this exception. rgman->requestQueueCheck(); diff --git a/src/FtpConnection.cc b/src/FtpConnection.cc index f690ae6b..b8d0f76a 100644 --- a/src/FtpConnection.cc +++ b/src/FtpConnection.cc @@ -53,8 +53,10 @@ #include "Socket.h" #include "A2STR.h" #include "StringFormat.h" +#include "fmt.h" #include "AuthConfig.h" #include "a2functional.h" +#include "util.h" namespace aria2 { @@ -62,15 +64,20 @@ const std::string FtpConnection::A("A"); const std::string FtpConnection::I("I"); -FtpConnection::FtpConnection(cuid_t cuid, const SocketHandle& socket, - const SharedHandle<Request>& req, - const SharedHandle<AuthConfig>& authConfig, - const Option* op): - cuid_(cuid), socket_(socket), req_(req), - authConfig_(authConfig), option_(op), - logger_(LogFactory::getInstance()), - socketBuffer_(socket), - baseWorkingDir_("/") {} +FtpConnection::FtpConnection +(cuid_t cuid, + const SocketHandle& socket, + const SharedHandle<Request>& req, + const SharedHandle<AuthConfig>& authConfig, + const Option* op) + : cuid_(cuid), + socket_(socket), + req_(req), + authConfig_(authConfig), + option_(op), + socketBuffer_(socket), + baseWorkingDir_("/") +{} FtpConnection::~FtpConnection() {} @@ -80,10 +87,8 @@ bool FtpConnection::sendUser() std::string request = "USER "; request += authConfig_->getUser(); request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(),"USER ********"); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), "USER ********")); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -96,10 +101,8 @@ bool FtpConnection::sendPass() std::string request = "PASS "; request += authConfig_->getPassword(); request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(),"PASS ********"); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), "PASS ********")); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -118,10 +121,8 @@ bool FtpConnection::sendType() std::string request = "TYPE "; request += type; request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(),request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(),request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -132,10 +133,8 @@ bool FtpConnection::sendPwd() { if(socketBuffer_.sendBufferIsEmpty()) { std::string request = "PWD\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(),request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(),request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -148,10 +147,8 @@ bool FtpConnection::sendCwd(const std::string& dir) std::string request = "CWD "; request += util::percentDecode(dir); request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(),request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(),request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -164,10 +161,8 @@ bool FtpConnection::sendMdtm() std::string request = "MDTM "; request += util::percentDecode(req_->getFile()); request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(), request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -180,10 +175,8 @@ bool FtpConnection::sendSize() std::string request = "SIZE "; request += util::percentDecode(req_->getFile()); request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(), request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -194,10 +187,8 @@ bool FtpConnection::sendEpsv() { if(socketBuffer_.sendBufferIsEmpty()) { static const std::string request("EPSV\r\n"); - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(), request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -208,10 +199,8 @@ bool FtpConnection::sendPasv() { if(socketBuffer_.sendBufferIsEmpty()) { static const std::string request("PASV\r\n"); - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(), request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -245,10 +234,8 @@ bool FtpConnection::sendEprt(const SharedHandle<SocketCore>& serverSocket) request += "|"; request += util::uitos(addrinfo.second); request += "|\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(), request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -277,10 +264,8 @@ bool FtpConnection::sendPort(const SharedHandle<SocketCore>& serverSocket) request += ","; request += util::uitos(addrinfo.second%256); request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(), request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -297,10 +282,8 @@ bool FtpConnection::sendRest(const SharedHandle<Segment>& segment) request += util::itos(segment->getPositionToWrite()); } request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(), request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -313,10 +296,8 @@ bool FtpConnection::sendRetr() std::string request = "RETR "; request += util::percentDecode(req_->getFile()); request += "\r\n"; - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, - util::itos(cuid_).c_str(), request.c_str()); - } + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, + util::itos(cuid_).c_str(), request.c_str())); socketBuffer_.pushStr(request); } socketBuffer_.send(); @@ -411,10 +392,9 @@ bool FtpConnection::bulkReceiveResponse if((length = findEndOfResponse(status, strbuf_)) != std::string::npos) { response.first = status; response.second = strbuf_.substr(0, length); - if(logger_->info()) { - logger_->info(MSG_RECEIVE_RESPONSE, - util::itos(cuid_).c_str(), response.second.c_str()); - } + A2_LOG_INFO(fmt(MSG_RECEIVE_RESPONSE, + util::itos(cuid_).c_str(), + response.second.c_str())); strbuf_.erase(0, length); return true; } else { diff --git a/src/FtpConnection.h b/src/FtpConnection.h index 51bcf3fe..6a33a33b 100644 --- a/src/FtpConnection.h +++ b/src/FtpConnection.h @@ -48,7 +48,6 @@ namespace aria2 { class Option; -class Logger; class Segment; class Request; class SocketCore; @@ -63,7 +62,6 @@ private: SharedHandle<AuthConfig> authConfig_; const Option* option_; - Logger* logger_; std::string strbuf_; diff --git a/src/FtpFinishDownloadCommand.cc b/src/FtpFinishDownloadCommand.cc index 64555cd7..d151b204 100644 --- a/src/FtpFinishDownloadCommand.cc +++ b/src/FtpFinishDownloadCommand.cc @@ -43,10 +43,12 @@ #include "FtpConnection.h" #include "message.h" #include "StringFormat.h" +#include "fmt.h" #include "DlAbortEx.h" #include "SocketCore.h" #include "RequestGroup.h" #include "Logger.h" +#include "LogFactory.h" #include "util.h" #include "wallclock.h" @@ -90,20 +92,21 @@ bool FtpFinishDownloadCommand::execute() getSocket(), options); } } else { - getLogger()->info("CUID#%s - Bad status for transfer complete.", - util::itos(getCuid()).c_str()); + A2_LOG_INFO(fmt("CUID#%s - Bad status for transfer complete.", + util::itos(getCuid()).c_str())); } } else if(getCheckPoint().difference(global::wallclock) >= getTimeout()) { - getLogger()->info("CUID#%s - Timeout before receiving transfer complete.", - util::itos(getCuid()).c_str()); + A2_LOG_INFO(fmt("CUID#%s - Timeout before receiving transfer complete.", + util::itos(getCuid()).c_str())); } else { getDownloadEngine()->addCommand(this); return false; } } catch(RecoverableException& e) { - getLogger()->info("CUID#%s - Exception was thrown, but download was" - " finished, so we can ignore the exception.", - e, util::itos(getCuid()).c_str()); + A2_LOG_INFO_EX(fmt("CUID#%s - Exception was thrown, but download was" + " finished, so we can ignore the exception.", + util::itos(getCuid()).c_str()), + e); } if(getRequestGroup()->downloadFinished()) { return true; diff --git a/src/FtpInitiateConnectionCommand.cc b/src/FtpInitiateConnectionCommand.cc index 7538f23e..f7f54c66 100644 --- a/src/FtpInitiateConnectionCommand.cc +++ b/src/FtpInitiateConnectionCommand.cc @@ -46,6 +46,7 @@ #include "FtpTunnelRequestCommand.h" #include "DlAbortEx.h" #include "Logger.h" +#include "LogFactory.h" #include "message.h" #include "prefs.h" #include "HttpConnection.h" @@ -53,6 +54,7 @@ #include "util.h" #include "AuthConfigFactory.h" #include "AuthConfig.h" +#include "fmt.h" namespace aria2 { @@ -88,10 +90,8 @@ Command* FtpInitiateConnectionCommand::createNextCommand proxyRequest->getHost(), proxyRequest->getPort()); } if(!pooledSocket) { - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_SERVER, - util::itos(getCuid()).c_str(), addr.c_str(), port); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, + util::itos(getCuid()).c_str(), addr.c_str(), port)); createSocket(); getSocket()->establishConnection(addr, port); @@ -153,10 +153,8 @@ Command* FtpInitiateConnectionCommand::createNextCommand getDownloadEngine()->getAuthConfigFactory()->createAuthConfig (getRequest(), getOption().get())->getUser()); if(!pooledSocket) { - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_SERVER, - util::itos(getCuid()).c_str(), addr.c_str(), port); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, + util::itos(getCuid()).c_str(), addr.c_str(), port)); createSocket(); getSocket()->establishConnection(addr, port); FtpNegotiationCommand* c = diff --git a/src/FtpNegotiationCommand.cc b/src/FtpNegotiationCommand.cc index 57040563..242a8005 100644 --- a/src/FtpNegotiationCommand.cc +++ b/src/FtpNegotiationCommand.cc @@ -52,6 +52,7 @@ #include "util.h" #include "Option.h" #include "Logger.h" +#include "LogFactory.h" #include "Segment.h" #include "DownloadContext.h" #include "DefaultBtProgressInfoFile.h" @@ -59,6 +60,7 @@ #include "DownloadFailureException.h" #include "Socket.h" #include "StringFormat.h" +#include "fmt.h" #include "DiskAdaptor.h" #include "SegmentMan.h" #include "AuthConfigFactory.h" @@ -253,10 +255,8 @@ bool FtpNegotiationCommand::recvPwd() throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str()); } ftp_->setBaseWorkingDir(pwd); - if(getLogger()->info()) { - getLogger()->info("CUID#%s - base working directory is '%s'", - util::itos(getCuid()).c_str(), pwd.c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - base working directory is '%s'", + util::itos(getCuid()).c_str(), pwd.c_str())); sequence_ = SEQ_SEND_CWD_PREP; return true; } @@ -332,21 +332,15 @@ bool FtpNegotiationCommand::recvMdtm() if(status == 213) { if(lastModifiedTime.good()) { getRequestGroup()->updateLastModifiedTime(lastModifiedTime); - if(getLogger()->debug()) { - getLogger()->debug("MDTM result was parsed as: %s", - lastModifiedTime.toHTTPDate().c_str()); - } + A2_LOG_DEBUG(fmt("MDTM result was parsed as: %s", + lastModifiedTime.toHTTPDate().c_str())); } else { - if(getLogger()->debug()) { - getLogger()->debug("MDTM response was returned, but it seems not to be" - " a time value as in specified in RFC3659."); - } + A2_LOG_DEBUG("MDTM response was returned, but it seems not to be" + " a time value as in specified in RFC3659."); } } else { - if(getLogger()->info()) { - getLogger()->info("CUID#%s - MDTM command failed.", - util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - MDTM command failed.", + util::itos(getCuid()).c_str())); } sequence_ = SEQ_SEND_SIZE; return true; @@ -403,10 +397,9 @@ bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength) getPieceStorage()->markAllPiecesDone(); getDownloadContext()->setChecksumVerified(true); sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED; - getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, - util::itos(getRequestGroup()->getGID()).c_str(), - getRequestGroup()->getFirstFilePath().c_str()); - + A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED, + util::itos(getRequestGroup()->getGID()).c_str(), + getRequestGroup()->getFirstFilePath().c_str())); poolConnection(); return false; @@ -482,10 +475,8 @@ bool FtpNegotiationCommand::recvSize() { } } else { - if(getLogger()->info()) { - getLogger()->info("CUID#%s - The remote FTP Server doesn't recognize SIZE" - " command. Continue.", util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - The remote FTP Server doesn't recognize SIZE" + " command. Continue.", util::itos(getCuid()).c_str())); // Even if one of the other servers waiting in the queue supports SIZE // command, resuming and segmented downloading are disabled when the first // contacted FTP server doesn't support it. @@ -648,11 +639,10 @@ bool FtpNegotiationCommand::preparePasvConnect() { return true; } else { // make a data connection to the server. - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_SERVER, util::itos(getCuid()).c_str(), - dataConnAddr_.first.c_str(), - dataConnAddr_.second); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, + util::itos(getCuid()).c_str(), + dataConnAddr_.first.c_str(), + dataConnAddr_.second)); dataSocket_.reset(new SocketCore()); dataSocket_->establishConnection(dataConnAddr_.first, dataConnAddr_.second); disableReadCheckSocket(); @@ -671,10 +661,9 @@ bool FtpNegotiationCommand::resolveProxy() if(proxyAddr_.empty()) { return false; } - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_SERVER, util::itos(getCuid()).c_str(), - proxyAddr_.c_str(), proxyReq->getPort()); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, + util::itos(getCuid()).c_str(), + proxyAddr_.c_str(), proxyReq->getPort())); dataSocket_.reset(new SocketCore()); dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort()); disableReadCheckSocket(); @@ -702,17 +691,13 @@ bool FtpNegotiationCommand::sendTunnelRequest() (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str()); } else { - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY, - util::itos(getCuid()).c_str(), - proxyAddr_.c_str(), proxyReq->getPort()); - } + A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY, + util::itos(getCuid()).c_str(), + proxyAddr_.c_str(), proxyReq->getPort())); proxyAddr_ = nextProxyAddr; - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_SERVER, - util::itos(getCuid()).c_str(), - proxyAddr_.c_str(), proxyReq->getPort()); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, + util::itos(getCuid()).c_str(), + proxyAddr_.c_str(), proxyReq->getPort())); dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort()); return false; } diff --git a/src/HandshakeExtensionMessage.cc b/src/HandshakeExtensionMessage.cc index c76f629b..925cc32a 100644 --- a/src/HandshakeExtensionMessage.cc +++ b/src/HandshakeExtensionMessage.cc @@ -40,6 +40,7 @@ #include "Logger.h" #include "message.h" #include "StringFormat.h" +#include "fmt.h" #include "bencode2.h" #include "DownloadContext.h" #include "bittorrent_helper.h" @@ -51,10 +52,10 @@ namespace aria2 { const std::string HandshakeExtensionMessage::EXTENSION_NAME = "handshake"; -HandshakeExtensionMessage::HandshakeExtensionMessage(): - tcpPort_(0), - metadataSize_(0), - logger_(LogFactory::getInstance()) {} +HandshakeExtensionMessage::HandshakeExtensionMessage() + : tcpPort_(0), + metadataSize_(0) +{} HandshakeExtensionMessage::~HandshakeExtensionMessage() {} @@ -175,11 +176,8 @@ HandshakeExtensionMessage::create(const unsigned char* data, size_t length) static_cast<unsigned long>(length)).str()); } HandshakeExtensionMessageHandle msg(new HandshakeExtensionMessage()); - if(LogFactory::getInstance()->debug()) { - LogFactory::getInstance()->debug - ("Creating HandshakeExtensionMessage from %s", - util::percentEncode(data, length).c_str()); - } + A2_LOG_DEBUG(fmt("Creating HandshakeExtensionMessage from %s", + util::percentEncode(data, length).c_str())); SharedHandle<ValueBase> decoded = bencode2::decode(data+1, length-1); const Dict* dict = asDict(decoded); if(!dict) { diff --git a/src/HandshakeExtensionMessage.h b/src/HandshakeExtensionMessage.h index a273c37b..f5650cff 100644 --- a/src/HandshakeExtensionMessage.h +++ b/src/HandshakeExtensionMessage.h @@ -44,7 +44,6 @@ namespace aria2 { class Peer; -class Logger; class DownloadContext; class HandshakeExtensionMessage:public ExtensionMessage { @@ -60,9 +59,6 @@ private: SharedHandle<DownloadContext> dctx_; SharedHandle<Peer> peer_; - - Logger* logger_; - public: HandshakeExtensionMessage(); diff --git a/src/HttpConnection.cc b/src/HttpConnection.cc index 7512bca4..36788773 100644 --- a/src/HttpConnection.cc +++ b/src/HttpConnection.cc @@ -55,20 +55,22 @@ #include "AuthConfigFactory.h" #include "AuthConfig.h" #include "a2functional.h" +#include "fmt.h" namespace aria2 { HttpRequestEntry::HttpRequestEntry -(const SharedHandle<HttpRequest>& httpRequest): - httpRequest_(httpRequest), - proc_(new HttpHeaderProcessor()) {} +(const SharedHandle<HttpRequest>& httpRequest) + : httpRequest_(httpRequest), + proc_(new HttpHeaderProcessor()) +{} HttpRequestEntry::~HttpRequestEntry() {} -HttpConnection::HttpConnection(cuid_t cuid, const SocketHandle& socket): - cuid_(cuid), socket_(socket), - socketBuffer_(socket), - logger_(LogFactory::getInstance()) +HttpConnection::HttpConnection(cuid_t cuid, const SocketHandle& socket) + : cuid_(cuid), + socket_(socket), + socketBuffer_(socket) {} HttpConnection::~HttpConnection() {} @@ -95,11 +97,9 @@ std::string HttpConnection::eraseConfidentialInfo(const std::string& request) void HttpConnection::sendRequest(const SharedHandle<HttpRequest>& httpRequest) { std::string request = httpRequest->createRequest(); - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, util::itos(cuid_).c_str(), - eraseConfidentialInfo(request).c_str()); - } + eraseConfidentialInfo(request).c_str())); socketBuffer_.pushStr(request); socketBuffer_.send(); SharedHandle<HttpRequestEntry> entry(new HttpRequestEntry(httpRequest)); @@ -110,11 +110,9 @@ void HttpConnection::sendProxyRequest (const SharedHandle<HttpRequest>& httpRequest) { std::string request = httpRequest->createProxyRequest(); - if(logger_->info()) { - logger_->info(MSG_SENDING_REQUEST, + A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, util::itos(cuid_).c_str(), - eraseConfidentialInfo(request).c_str()); - } + eraseConfidentialInfo(request).c_str())); socketBuffer_.pushStr(request); socketBuffer_.send(); SharedHandle<HttpRequestEntry> entry(new HttpRequestEntry(httpRequest)); @@ -147,10 +145,9 @@ SharedHandle<HttpResponse> HttpConnection::receiveResponse() size_t putbackDataLength = proc->getPutBackDataLength(); size -= putbackDataLength; socket_->readData(buf, size); - if(logger_->info()) { - logger_->info(MSG_RECEIVE_RESPONSE, - util::itos(cuid_).c_str(), proc->getHeaderString().c_str()); - } + A2_LOG_INFO(fmt(MSG_RECEIVE_RESPONSE, + util::itos(cuid_).c_str(), + proc->getHeaderString().c_str())); SharedHandle<HttpHeader> httpHeader = proc->getHttpResponseHeader(); SharedHandle<HttpResponse> httpResponse(new HttpResponse()); httpResponse->setCuid(cuid_); diff --git a/src/HttpConnection.h b/src/HttpConnection.h index 6d1c9524..9c7facea 100644 --- a/src/HttpConnection.h +++ b/src/HttpConnection.h @@ -50,7 +50,6 @@ class HttpRequest; class HttpResponse; class HttpHeaderProcessor; class Option; -class Logger; class Segment; class SocketCore; @@ -83,7 +82,6 @@ private: SharedHandle<SocketCore> socket_; SocketBuffer socketBuffer_; const Option* option_; - Logger* logger_; HttpRequestEntries outstandingHttpRequests_; diff --git a/src/HttpInitiateConnectionCommand.cc b/src/HttpInitiateConnectionCommand.cc index e625f470..0d9a11ab 100644 --- a/src/HttpInitiateConnectionCommand.cc +++ b/src/HttpInitiateConnectionCommand.cc @@ -43,11 +43,13 @@ #include "DlAbortEx.h" #include "Option.h" #include "Logger.h" +#include "LogFactory.h" #include "Socket.h" #include "message.h" #include "prefs.h" #include "A2STR.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -56,8 +58,9 @@ HttpInitiateConnectionCommand::HttpInitiateConnectionCommand const SharedHandle<Request>& req, const SharedHandle<FileEntry>& fileEntry, RequestGroup* requestGroup, - DownloadEngine* e): - InitiateConnectionCommand(cuid, req, fileEntry, requestGroup, e) {} + DownloadEngine* e) + : InitiateConnectionCommand(cuid, req, fileEntry, requestGroup, e) +{} HttpInitiateConnectionCommand::~HttpInitiateConnectionCommand() {} @@ -74,10 +77,8 @@ Command* HttpInitiateConnectionCommand::createNextCommand proxyRequest->getHost(), proxyRequest->getPort()); std::string proxyMethod = resolveProxyMethod(getRequest()->getProtocol()); if(!pooledSocket) { - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_SERVER, - util::itos(getCuid()).c_str(), addr.c_str(), port); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, + util::itos(getCuid()).c_str(), addr.c_str(), port)); createSocket(); getSocket()->establishConnection(addr, port); @@ -129,10 +130,8 @@ Command* HttpInitiateConnectionCommand::createNextCommand getDownloadEngine()->popPooledSocket (resolvedAddresses, getRequest()->getPort()); if(!pooledSocket) { - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_SERVER, - util::itos(getCuid()).c_str(), addr.c_str(), port); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, + util::itos(getCuid()).c_str(), addr.c_str(), port)); createSocket(); getSocket()->establishConnection(addr, port); getRequest()->setConnectedAddrInfo(hostname, addr, port); diff --git a/src/HttpListenCommand.cc b/src/HttpListenCommand.cc index 9a59a530..a0dd3c10 100644 --- a/src/HttpListenCommand.cc +++ b/src/HttpListenCommand.cc @@ -37,6 +37,7 @@ #include "RecoverableException.h" #include "message.h" #include "Logger.h" +#include "LogFactory.h" #include "SocketCore.h" #include "HttpServerCommand.h" #include "CUIDCounter.h" @@ -45,12 +46,15 @@ #include "Option.h" #include "util.h" #include "A2STR.h" +#include "fmt.h" namespace aria2 { -HttpListenCommand::HttpListenCommand -(cuid_t cuid, DownloadEngine* e, int family): - Command(cuid), e_(e), family_(family) {} +HttpListenCommand::HttpListenCommand(cuid_t cuid, DownloadEngine* e, int family) + : Command(cuid), + e_(e), + family_(family) +{} HttpListenCommand::~HttpListenCommand() { @@ -72,8 +76,8 @@ bool HttpListenCommand::execute() std::pair<std::string, uint16_t> peerInfo; socket->getPeerInfo(peerInfo); - getLogger()->info("XML-RPC: Accepted the connection from %s:%u.", - peerInfo.first.c_str(), peerInfo.second); + A2_LOG_INFO(fmt("XML-RPC: Accepted the connection from %s:%u.", + peerInfo.first.c_str(), peerInfo.second)); HttpServerCommand* c = new HttpServerCommand(e_->newCUID(), e_, socket); @@ -81,9 +85,7 @@ bool HttpListenCommand::execute() e_->addCommand(c); } } catch(RecoverableException& e) { - if(getLogger()->debug()) { - getLogger()->debug(MSG_ACCEPT_FAILURE, e, util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG_EX(fmt(MSG_ACCEPT_FAILURE, util::itos(getCuid()).c_str()), e); } e_->addCommand(this); return false; @@ -95,11 +97,9 @@ bool HttpListenCommand::bindPort(uint16_t port) e_->deleteSocketForReadCheck(serverSocket_, this); } serverSocket_.reset(new SocketCore()); - if(getLogger()->info()) { - getLogger()->info("CUID#%s - Setting up HttpListenCommand for IPv%d", - util::itos(getCuid()).c_str(), - family_ == AF_INET?4:6); - } + A2_LOG_INFO(fmt("CUID#%s - Setting up HttpListenCommand for IPv%d", + util::itos(getCuid()).c_str(), + family_ == AF_INET?4:6)); try { int flags = 0; if(e_->getOption()->getAsBool(PREF_XML_RPC_LISTEN_ALL)) { @@ -108,17 +108,16 @@ bool HttpListenCommand::bindPort(uint16_t port) serverSocket_->bind(A2STR::NIL, port, family_, flags); serverSocket_->beginListen(); serverSocket_->setNonBlockingMode(); - if(getLogger()->info()) { - getLogger()->info(MSG_LISTENING_PORT, - util::itos(getCuid()).c_str(), port); - } + A2_LOG_INFO(fmt(MSG_LISTENING_PORT, + util::itos(getCuid()).c_str(), port)); e_->addSocketForReadCheck(serverSocket_, this); return true; } catch(RecoverableException& e) { - getLogger()->error("Failed to setup XML-RPC server for IPv%d", - family_ == AF_INET?4:6); - getLogger()->error(MSG_BIND_FAILURE, e, - util::itos(getCuid()).c_str(), port); + A2_LOG_ERROR(fmt("Failed to setup XML-RPC server for IPv%d", + family_ == AF_INET?4:6)); + A2_LOG_ERROR_EX(fmt(MSG_BIND_FAILURE, + util::itos(getCuid()).c_str(), port), + e); if(serverSocket_) { e_->deleteSocketForReadCheck(serverSocket_, this); } diff --git a/src/HttpRequestCommand.cc b/src/HttpRequestCommand.cc index 54bfb91c..8d9919dd 100644 --- a/src/HttpRequestCommand.cc +++ b/src/HttpRequestCommand.cc @@ -56,6 +56,8 @@ #include "PieceStorage.h" #include "DefaultBtProgressInfoFile.h" #include "Logger.h" +#include "LogFactory.h" +#include "fmt.h" namespace aria2 { @@ -67,8 +69,8 @@ HttpRequestCommand::HttpRequestCommand const HttpConnectionHandle& httpConnection, DownloadEngine* e, const SocketHandle& s) - :AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), - httpConnection_(httpConnection) + : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), + httpConnection_(httpConnection) { setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)); disableReadCheckSocket(); @@ -150,10 +152,8 @@ bool HttpRequestCommand::executeInternal() { getRequest()->getProtocol() == Request::PROTO_HTTPS)) { if(getFileEntry()->getPath().empty() && getRequest()->getFile().empty()) { - if(getLogger()->debug()) { - getLogger()->debug("conditional-get is disabled because file name" - "is not available."); - } + A2_LOG_DEBUG("Conditional-Get is disabled because file name" + " is not available."); } else { if(getFileEntry()->getPath().empty()) { getFileEntry()->setPath diff --git a/src/HttpResponse.cc b/src/HttpResponse.cc index 1abe0148..963b84bd 100644 --- a/src/HttpResponse.cc +++ b/src/HttpResponse.cc @@ -45,6 +45,7 @@ #include "DlAbortEx.h" #include "DlRetryEx.h" #include "StringFormat.h" +#include "fmt.h" #include "A2STR.h" #include "CookieStorage.h" #include "AuthConfigFactory.h" @@ -56,8 +57,8 @@ namespace aria2 { -HttpResponse::HttpResponse():cuid_(0), - logger_(LogFactory::getInstance()) +HttpResponse::HttpResponse() + : cuid_(0) {} HttpResponse::~HttpResponse() {} @@ -117,10 +118,9 @@ std::string HttpResponse::determinFilename() const return file; } } else { - if(logger_->info()) { - logger_->info(MSG_CONTENT_DISPOSITION_DETECTED, - util::itos(cuid_).c_str(), contentDisposition.c_str()); - } + A2_LOG_INFO(fmt(MSG_CONTENT_DISPOSITION_DETECTED, + util::itos(cuid_).c_str(), + contentDisposition.c_str())); return contentDisposition; } } @@ -150,10 +150,9 @@ void HttpResponse::processRedirect() { if(httpRequest_->getRequest()->redirectUri(getRedirectURI())) { - if(logger_->info()) { - logger_->info(MSG_REDIRECT, util::itos(cuid_).c_str(), - httpRequest_->getRequest()->getCurrentUri().c_str()); - } + A2_LOG_INFO(fmt(MSG_REDIRECT, + util::itos(cuid_).c_str(), + httpRequest_->getRequest()->getCurrentUri().c_str())); } else { throw DL_RETRY_EX (StringFormat("CUID#%s - Redirect to %s failed. It may not be a valid" diff --git a/src/HttpResponse.h b/src/HttpResponse.h index 807b6083..f818e7cc 100644 --- a/src/HttpResponse.h +++ b/src/HttpResponse.h @@ -47,7 +47,6 @@ namespace aria2 { class HttpRequest; class HttpHeader; -class Logger; class StreamFilter; class HttpResponse { @@ -55,7 +54,6 @@ private: cuid_t cuid_; SharedHandle<HttpRequest> httpRequest_; SharedHandle<HttpHeader> httpHeader_; - Logger* logger_; public: HttpResponse(); diff --git a/src/HttpResponseCommand.cc b/src/HttpResponseCommand.cc index 01628a3f..82ac7333 100644 --- a/src/HttpResponseCommand.cc +++ b/src/HttpResponseCommand.cc @@ -58,6 +58,7 @@ #include "message.h" #include "prefs.h" #include "StringFormat.h" +#include "fmt.h" #include "HttpSkipResponseCommand.h" #include "HttpHeader.h" #include "LogFactory.h" @@ -109,11 +110,11 @@ SharedHandle<StreamFilter> getContentEncodingStreamFilter if(httpResponse->isContentEncodingSpecified()) { filter = httpResponse->getContentEncodingStreamFilter(); if(!filter) { - LogFactory::getInstance()->info - ("Content-Encoding %s is specified, but the current implementation" - "doesn't support it. The decoding process is skipped and the" - "downloaded content will be still encoded.", - httpResponse->getContentEncoding().c_str()); + A2_LOG_INFO + (fmt("Content-Encoding %s is specified, but the current implementation" + "doesn't support it. The decoding process is skipped and the" + "downloaded content will be still encoded.", + httpResponse->getContentEncoding().c_str())); } else { filter->init(); filter->installDelegate(delegate); @@ -134,8 +135,8 @@ HttpResponseCommand::HttpResponseCommand const HttpConnectionHandle& httpConnection, DownloadEngine* e, const SocketHandle& s) - :AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), - httpConnection_(httpConnection) + : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), + httpConnection_(httpConnection) {} HttpResponseCommand::~HttpResponseCommand() {} @@ -176,9 +177,9 @@ bool HttpResponseCommand::executeInternal() getPieceStorage()->markAllPiecesDone(); // Just set checksum verification done. getDownloadContext()->setChecksumVerified(true); - getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, - util::itos(getRequestGroup()->getGID()).c_str(), - getRequestGroup()->getFirstFilePath().c_str()); + A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED, + util::itos(getRequestGroup()->getGID()).c_str(), + getRequestGroup()->getFirstFilePath().c_str())); poolConnection(); getFileEntry()->poolRequest(getRequest()); return true; @@ -382,9 +383,9 @@ bool HttpResponseCommand::handleOtherEncoding getRequestGroup()->initPieceStorage(); getPieceStorage()->markAllPiecesDone(); getDownloadContext()->setChecksumVerified(true); - getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, - util::itos(getRequestGroup()->getGID()).c_str(), - getRequestGroup()->getFirstFilePath().c_str()); + A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED, + util::itos(getRequestGroup()->getGID()).c_str(), + getRequestGroup()->getFirstFilePath().c_str())); poolConnection(); return true; } diff --git a/src/HttpServer.cc b/src/HttpServer.cc index 4f1e5e92..fd8f9b6b 100644 --- a/src/HttpServer.cc +++ b/src/HttpServer.cc @@ -46,20 +46,21 @@ #include "Logger.h" #include "Base64.h" #include "a2functional.h" +#include "fmt.h" namespace aria2 { -HttpServer::HttpServer(const SharedHandle<SocketCore>& socket, - DownloadEngine* e): - socket_(socket), - socketBuffer_(socket), - e_(e), - headerProcessor_(new HttpHeaderProcessor()), - logger_(LogFactory::getInstance()), - keepAlive_(true), - gzip_(false), - acceptsPersistentConnection_(true), - acceptsGZip_(false) +HttpServer::HttpServer +(const SharedHandle<SocketCore>& socket, + DownloadEngine* e) + : socket_(socket), + socketBuffer_(socket), + e_(e), + headerProcessor_(new HttpHeaderProcessor()), + keepAlive_(true), + gzip_(false), + acceptsPersistentConnection_(true), + acceptsGZip_(false) {} HttpServer::~HttpServer() {} @@ -83,8 +84,8 @@ SharedHandle<HttpHeader> HttpServer::receiveRequest() SharedHandle<HttpHeader> header = headerProcessor_->getHttpRequestHeader(); if(header) { - logger_->info("HTTP Server received request\n%s", - headerProcessor_->getHeaderString().c_str()); + A2_LOG_INFO(fmt("HTTP Server received request\n%s", + headerProcessor_->getHeaderString().c_str())); lastRequestHeader_ = header; lastBody_.clear(); lastBody_.str(""); @@ -165,9 +166,7 @@ void HttpServer::feedResponse(const std::string& status, } header += "\r\n"; - if(logger_->debug()) { - logger_->debug("HTTP Server sends response:\n%s", header.c_str()); - } + A2_LOG_DEBUG(fmt("HTTP Server sends response:\n%s", header.c_str())); socketBuffer_.pushStr(header); socketBuffer_.pushStr(text); } diff --git a/src/HttpServer.h b/src/HttpServer.h index 19f5358f..56b982f3 100644 --- a/src/HttpServer.h +++ b/src/HttpServer.h @@ -50,7 +50,6 @@ class SocketCore; class HttpHeader; class HttpHeaderProcessor; class DownloadEngine; -class Logger; class HttpServer { private: @@ -58,7 +57,6 @@ private: SocketBuffer socketBuffer_; DownloadEngine* e_; SharedHandle<HttpHeaderProcessor> headerProcessor_; - Logger* logger_; SharedHandle<HttpHeader> lastRequestHeader_; uint64_t lastContentLength_; std::stringstream lastBody_; diff --git a/src/HttpServerBodyCommand.cc b/src/HttpServerBodyCommand.cc index 7246ef16..441ed40b 100644 --- a/src/HttpServerBodyCommand.cc +++ b/src/HttpServerBodyCommand.cc @@ -38,6 +38,7 @@ #include "HttpServer.h" #include "HttpHeader.h" #include "Logger.h" +#include "LogFactory.h" #include "RequestGroup.h" #include "RequestGroupMan.h" #include "RecoverableException.h" @@ -51,6 +52,7 @@ #include "XmlRpcResponse.h" #include "wallclock.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -58,11 +60,11 @@ HttpServerBodyCommand::HttpServerBodyCommand (cuid_t cuid, const SharedHandle<HttpServer>& httpServer, DownloadEngine* e, - const SharedHandle<SocketCore>& socket): - Command(cuid), - e_(e), - socket_(socket), - httpServer_(httpServer) + const SharedHandle<SocketCore>& socket) + : Command(cuid), + e_(e), + socket_(socket), + httpServer_(httpServer) { setStatus(Command::STATUS_ONESHOT_REALTIME); e_->addSocketForReadCheck(socket_, this); @@ -108,7 +110,7 @@ bool HttpServerBodyCommand::execute() } } else { if(timeoutTimer_.difference(global::wallclock) >= 30) { - getLogger()->info("HTTP request body timeout."); + A2_LOG_INFO("HTTP request body timeout."); return true; } else { e_->addCommand(this); @@ -116,11 +118,10 @@ bool HttpServerBodyCommand::execute() } } } catch(RecoverableException& e) { - if(getLogger()->info()) { - getLogger()->info - ("CUID#%s - Error occurred while reading HTTP request body", - e, util::itos(getCuid()).c_str()); - } + A2_LOG_INFO_EX + (fmt("CUID#%s - Error occurred while reading HTTP request body", + util::itos(getCuid()).c_str()), + e); return true; } diff --git a/src/HttpServerCommand.cc b/src/HttpServerCommand.cc index 0a76d011..4e7d42d0 100644 --- a/src/HttpServerCommand.cc +++ b/src/HttpServerCommand.cc @@ -38,6 +38,7 @@ #include "HttpServer.h" #include "HttpHeader.h" #include "Logger.h" +#include "LogFactory.h" #include "RequestGroup.h" #include "RequestGroupMan.h" #include "HttpServerBodyCommand.h" @@ -47,15 +48,18 @@ #include "Option.h" #include "util.h" #include "wallclock.h" +#include "fmt.h" namespace aria2 { -HttpServerCommand::HttpServerCommand(cuid_t cuid, DownloadEngine* e, - const SharedHandle<SocketCore>& socket): - Command(cuid), - e_(e), - socket_(socket), - httpServer_(new HttpServer(socket, e)) +HttpServerCommand::HttpServerCommand +(cuid_t cuid, + DownloadEngine* e, + const SharedHandle<SocketCore>& socket) + : Command(cuid), + e_(e), + socket_(socket), + httpServer_(new HttpServer(socket, e)) { setStatus(Command::STATUS_ONESHOT_REALTIME); e_->addSocketForReadCheck(socket_, this); @@ -68,14 +72,15 @@ HttpServerCommand::HttpServerCommand(cuid_t cuid, DownloadEngine* e, #endif // !HAVE_LIBZ } -HttpServerCommand::HttpServerCommand(cuid_t cuid, - const SharedHandle<HttpServer>& httpServer, - DownloadEngine* e, - const SharedHandle<SocketCore>& socket): - Command(cuid), - e_(e), - socket_(socket), - httpServer_(httpServer) +HttpServerCommand::HttpServerCommand +(cuid_t cuid, + const SharedHandle<HttpServer>& httpServer, + DownloadEngine* e, + const SharedHandle<SocketCore>& socket) + : Command(cuid), + e_(e), + socket_(socket), + httpServer_(httpServer) { e_->addSocketForReadCheck(socket_, this); } @@ -115,10 +120,10 @@ bool HttpServerCommand::execute() if(static_cast<uint64_t> (e_->getOption()->getAsInt(PREF_XML_RPC_MAX_REQUEST_SIZE)) < httpServer_->getContentLength()) { - getLogger()->info("Request too long. ContentLength=%s." - " See --xml-rpc-max-request-size option to loose" - " this limitation.", - util::uitos(httpServer_->getContentLength()).c_str()); + A2_LOG_INFO(fmt("Request too long. ContentLength=%s." + " See --xml-rpc-max-request-size option to loose" + " this limitation.", + util::uitos(httpServer_->getContentLength()).c_str())); return true; } Command* command = new HttpServerBodyCommand(getCuid(), httpServer_, e_, @@ -128,7 +133,7 @@ bool HttpServerCommand::execute() return true; } else { if(timeoutTimer_.difference(global::wallclock) >= 30) { - getLogger()->info("HTTP request timeout."); + A2_LOG_INFO("HTTP request timeout."); return true; } else { e_->addCommand(this); @@ -136,10 +141,9 @@ bool HttpServerCommand::execute() } } } catch(RecoverableException& e) { - if(getLogger()->info()) { - getLogger()->info("CUID#%s - Error occurred while reading HTTP request", - e, util::itos(getCuid()).c_str()); - } + A2_LOG_INFO_EX(fmt("CUID#%s - Error occurred while reading HTTP request", + util::itos(getCuid()).c_str()), + e); return true; } diff --git a/src/HttpServerResponseCommand.cc b/src/HttpServerResponseCommand.cc index c234c76a..f282cf45 100644 --- a/src/HttpServerResponseCommand.cc +++ b/src/HttpServerResponseCommand.cc @@ -37,11 +37,13 @@ #include "DownloadEngine.h" #include "HttpServer.h" #include "Logger.h" +#include "LogFactory.h" #include "HttpServerCommand.h" #include "RequestGroupMan.h" #include "RecoverableException.h" #include "wallclock.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -49,11 +51,11 @@ HttpServerResponseCommand::HttpServerResponseCommand (cuid_t cuid, const SharedHandle<HttpServer>& httpServer, DownloadEngine* e, - const SharedHandle<SocketCore>& socket): - Command(cuid), - e_(e), - socket_(socket), - httpServer_(httpServer) + const SharedHandle<SocketCore>& socket) + : Command(cuid), + e_(e), + socket_(socket), + httpServer_(httpServer) { setStatus(Command::STATUS_ONESHOT_REALTIME); e_->addSocketForWriteCheck(socket_, this); @@ -72,33 +74,27 @@ bool HttpServerResponseCommand::execute() try { httpServer_->sendResponse(); } catch(RecoverableException& e) { - if(getLogger()->info()) { - getLogger()->info - ("CUID#%s - Error occurred while transmitting response body.", - e, util::itos(getCuid()).c_str()); - } + A2_LOG_INFO_EX + (fmt("CUID#%s - Error occurred while transmitting response body.", + util::itos(getCuid()).c_str()), + e); return true; } if(httpServer_->sendBufferIsEmpty()) { - if(getLogger()->info()) { - getLogger()->info("CUID#%s - HttpServer: all response transmitted.", - util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - HttpServer: all response transmitted.", + util::itos(getCuid()).c_str())); if(httpServer_->supportsPersistentConnection()) { - if(getLogger()->info()) { - getLogger()->info("CUID#%s - Persist connection.", - util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - Persist connection.", + util::itos(getCuid()).c_str())); e_->addCommand (new HttpServerCommand(getCuid(), httpServer_, e_, socket_)); } return true; } else { if(timeoutTimer_.difference(global::wallclock) >= 10) { - if(getLogger()->info()) { - getLogger()->info("CUID#%s - HttpServer: Timeout while trasmitting" - " response.", util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - HttpServer: Timeout while trasmitting" + " response.", + util::itos(getCuid()).c_str())); return true; } else { e_->addCommand(this); diff --git a/src/HttpSkipResponseCommand.cc b/src/HttpSkipResponseCommand.cc index b38ea7d0..96ca1bbe 100644 --- a/src/HttpSkipResponseCommand.cc +++ b/src/HttpSkipResponseCommand.cc @@ -41,10 +41,12 @@ #include "Request.h" #include "DownloadEngine.h" #include "Logger.h" +#include "LogFactory.h" #include "HttpRequest.h" #include "Segment.h" #include "util.h" #include "StringFormat.h" +#include "fmt.h" #include "DlAbortEx.h" #include "HttpHeader.h" #include "prefs.h" @@ -68,14 +70,14 @@ HttpSkipResponseCommand::HttpSkipResponseCommand const SharedHandle<HttpConnection>& httpConnection, const SharedHandle<HttpResponse>& httpResponse, DownloadEngine* e, - const SharedHandle<SocketCore>& s): - AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), - httpConnection_(httpConnection), - httpResponse_(httpResponse), - streamFilter_(new NullSinkStreamFilter()), - sinkFilterOnly_(true), - totalLength_(httpResponse_->getEntityLength()), - receivedBytes_(0) + const SharedHandle<SocketCore>& s) + : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), + httpConnection_(httpConnection), + httpResponse_(httpResponse), + streamFilter_(new NullSinkStreamFilter()), + sinkFilterOnly_(true), + totalLength_(httpResponse_->getEntityLength()), + receivedBytes_(0) {} HttpSkipResponseCommand::~HttpSkipResponseCommand() {} @@ -133,9 +135,7 @@ bool HttpSkipResponseCommand::executeInternal() throw DL_RETRY_EX(EX_GOT_EOF); } } catch(RecoverableException& e) { - if(getLogger()->debug()) { - getLogger()->debug(EX_EXCEPTION_CAUGHT, e); - } + A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, e) return processResponse(); } diff --git a/src/InitiateConnectionCommand.cc b/src/InitiateConnectionCommand.cc index e58da6c7..ca96d12a 100644 --- a/src/InitiateConnectionCommand.cc +++ b/src/InitiateConnectionCommand.cc @@ -37,6 +37,7 @@ #include "DownloadEngine.h" #include "Option.h" #include "Logger.h" +#include "LogFactory.h" #include "message.h" #include "prefs.h" #include "NameResolver.h" @@ -48,6 +49,7 @@ #include "InitiateConnectionCommandFactory.h" #include "util.h" #include "RecoverableException.h" +#include "fmt.h" namespace aria2 { @@ -56,8 +58,8 @@ InitiateConnectionCommand::InitiateConnectionCommand const SharedHandle<Request>& req, const SharedHandle<FileEntry>& fileEntry, RequestGroup* requestGroup, - DownloadEngine* e): - AbstractCommand(cuid, req, fileEntry, requestGroup, e) + DownloadEngine* e) + : AbstractCommand(cuid, req, fileEntry, requestGroup, e) { setTimeout(getOption()->getAsInt(PREF_DNS_TIMEOUT)); // give a chance to be executed in the next loop in DownloadEngine @@ -97,11 +99,10 @@ bool InitiateConnectionCommand::executeInternal() { // TODO ipaddr might not be used if pooled sockt was found. getDownloadEngine()->markBadIPAddress(hostname, ipaddr, port); if(!getDownloadEngine()->findCachedIPAddress(hostname, port).empty()) { - if(getLogger()->info()) { - getLogger()->info(EX_EXCEPTION_CAUGHT, ex); - getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY, - util::itos(getCuid()).c_str(), ipaddr.c_str(), port); - } + A2_LOG_INFO_EX(EX_EXCEPTION_CAUGHT, ex); + A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY, + util::itos(getCuid()).c_str(), + ipaddr.c_str(), port)); Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand (getCuid(), getRequest(), getFileEntry(), getRequestGroup(), diff --git a/src/InitiatorMSEHandshakeCommand.cc b/src/InitiatorMSEHandshakeCommand.cc index d9bf4289..c59d95c5 100644 --- a/src/InitiatorMSEHandshakeCommand.cc +++ b/src/InitiatorMSEHandshakeCommand.cc @@ -41,6 +41,7 @@ #include "prefs.h" #include "Socket.h" #include "Logger.h" +#include "LogFactory.h" #include "Peer.h" #include "PeerConnection.h" #include "BtRuntime.h" @@ -54,6 +55,7 @@ #include "DownloadContext.h" #include "bittorrent_helper.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -63,13 +65,12 @@ InitiatorMSEHandshakeCommand::InitiatorMSEHandshakeCommand const SharedHandle<Peer>& p, DownloadEngine* e, const SharedHandle<BtRuntime>& btRuntime, - const SharedHandle<SocketCore>& s): - - PeerAbstractCommand(cuid, p, e, s), - requestGroup_(requestGroup), - btRuntime_(btRuntime), - sequence_(INITIATOR_SEND_KEY), - mseHandshake_(new MSEHandshake(cuid, s, getOption().get())) + const SharedHandle<SocketCore>& s) + : PeerAbstractCommand(cuid, p, e, s), + requestGroup_(requestGroup), + btRuntime_(btRuntime), + sequence_(INITIATOR_SEND_KEY), + mseHandshake_(new MSEHandshake(cuid, s, getOption().get())) { disableReadCheckSocket(); setWriteCheckSocket(getSocket()); @@ -172,12 +173,9 @@ bool InitiatorMSEHandshakeCommand::executeInternal() { bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait) { if(getOption()->getAsBool(PREF_BT_REQUIRE_CRYPTO)) { - if(getLogger()->info()) { - getLogger()->info - ("CUID#%s - Establishing connection using legacy BitTorrent" - " handshake is disabled by preference.", - util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - Establishing connection using legacy BitTorrent" + " handshake is disabled by preference.", + util::itos(getCuid()).c_str())); if(peerStorage_->isPeerAvailable() && btRuntime_->lessThanEqMinPeers()) { SharedHandle<Peer> peer = peerStorage_->getUnusedPeer(); peer->usedBy(getDownloadEngine()->newCUID()); @@ -191,10 +189,8 @@ bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait) return true; } else { // try legacy BitTorrent handshake - if(getLogger()->info()) { - getLogger()->info("CUID#%s - Retry using legacy BitTorrent handshake.", - util::itos(getCuid()).c_str()); - } + A2_LOG_INFO(fmt("CUID#%s - Retry using legacy BitTorrent handshake.", + util::itos(getCuid()).c_str())); PeerInitiateConnectionCommand* command = new PeerInitiateConnectionCommand(getCuid(), requestGroup_, getPeer(), getDownloadEngine(), btRuntime_, false); diff --git a/src/IteratableChecksumValidator.cc b/src/IteratableChecksumValidator.cc index 02f41869..26f75db7 100644 --- a/src/IteratableChecksumValidator.cc +++ b/src/IteratableChecksumValidator.cc @@ -40,8 +40,6 @@ #include "message.h" #include "PieceStorage.h" #include "MessageDigest.h" -#include "LogFactory.h" -#include "Logger.h" #include "DiskAdaptor.h" #include "FileEntry.h" #include "BitfieldMan.h" @@ -54,12 +52,12 @@ namespace aria2 { IteratableChecksumValidator::IteratableChecksumValidator (const SharedHandle<DownloadContext>& dctx, - const PieceStorageHandle& pieceStorage): - dctx_(dctx), - pieceStorage_(pieceStorage), - currentOffset_(0), - logger_(LogFactory::getInstance()), - buffer_(0) {} + const PieceStorageHandle& pieceStorage) + : dctx_(dctx), + pieceStorage_(pieceStorage), + currentOffset_(0), + buffer_(0) +{} IteratableChecksumValidator::~IteratableChecksumValidator() { diff --git a/src/IteratableChecksumValidator.h b/src/IteratableChecksumValidator.h index 6f788c62..bdc20f82 100644 --- a/src/IteratableChecksumValidator.h +++ b/src/IteratableChecksumValidator.h @@ -41,7 +41,6 @@ namespace aria2 { class DownloadContext; class PieceStorage; -class Logger; class MessageDigest; class IteratableChecksumValidator:public IteratableValidator @@ -55,10 +54,7 @@ private: SharedHandle<MessageDigest> ctx_; - Logger* logger_; - unsigned char* buffer_; - public: IteratableChecksumValidator(const SharedHandle<DownloadContext>& dctx, const SharedHandle<PieceStorage>& pieceStorage); diff --git a/src/IteratableChunkChecksumValidator.cc b/src/IteratableChunkChecksumValidator.cc index 7b251b56..c234cbf6 100644 --- a/src/IteratableChunkChecksumValidator.cc +++ b/src/IteratableChunkChecksumValidator.cc @@ -50,6 +50,7 @@ #include "Logger.h" #include "MessageDigest.h" #include "StringFormat.h" +#include "fmt.h" #include "DlAbortEx.h" namespace aria2 { @@ -57,15 +58,16 @@ namespace aria2 { #define BUFSIZE (256*1024) #define ALIGNMENT 512 -IteratableChunkChecksumValidator:: -IteratableChunkChecksumValidator(const SharedHandle<DownloadContext>& dctx, - const PieceStorageHandle& pieceStorage): - dctx_(dctx), - pieceStorage_(pieceStorage), - bitfield_(new BitfieldMan(dctx_->getPieceLength(), dctx_->getTotalLength())), - currentIndex_(0), - logger_(LogFactory::getInstance()), - buffer_(0) {} +IteratableChunkChecksumValidator::IteratableChunkChecksumValidator +(const SharedHandle<DownloadContext>& dctx, + const PieceStorageHandle& pieceStorage) + : dctx_(dctx), + pieceStorage_(pieceStorage), + bitfield_(new BitfieldMan(dctx_->getPieceLength(), + dctx_->getTotalLength())), + currentIndex_(0), + buffer_(0) +{} IteratableChunkChecksumValidator::~IteratableChunkChecksumValidator() { @@ -86,21 +88,19 @@ void IteratableChunkChecksumValidator::validateChunk() if(actualChecksum == dctx_->getPieceHashes()[currentIndex_]) { bitfield_->setBit(currentIndex_); } else { - if(logger_->info()) { - logger_->info(EX_INVALID_CHUNK_CHECKSUM, + A2_LOG_INFO(fmt(EX_INVALID_CHUNK_CHECKSUM, static_cast<unsigned long>(currentIndex_), util::itos(getCurrentOffset(), true).c_str(), dctx_->getPieceHashes()[currentIndex_].c_str(), - actualChecksum.c_str()); - } + actualChecksum.c_str())); bitfield_->unsetBit(currentIndex_); } } catch(RecoverableException& ex) { - if(logger_->debug()) { - logger_->debug("Caught exception while validating piece index=%lu." - " Some part of file may be missing. Continue operation.", - ex, static_cast<unsigned long>(currentIndex_)); - } + A2_LOG_DEBUG_EX(fmt("Caught exception while validating piece index=%lu." + " Some part of file may be missing." + " Continue operation.", + static_cast<unsigned long>(currentIndex_)), + ex); bitfield_->unsetBit(currentIndex_); } diff --git a/src/IteratableChunkChecksumValidator.h b/src/IteratableChunkChecksumValidator.h index ff011ff2..46f41b5c 100644 --- a/src/IteratableChunkChecksumValidator.h +++ b/src/IteratableChunkChecksumValidator.h @@ -42,7 +42,6 @@ namespace aria2 { class DownloadContext; class PieceStorage; class BitfieldMan; -class Logger; class MessageDigest; class IteratableChunkChecksumValidator:public IteratableValidator @@ -52,7 +51,6 @@ private: SharedHandle<PieceStorage> pieceStorage_; SharedHandle<BitfieldMan> bitfield_; size_t currentIndex_; - Logger* logger_; SharedHandle<MessageDigest> ctx_; unsigned char* buffer_; diff --git a/src/KqueueEventPoll.cc b/src/KqueueEventPoll.cc index dfa500b4..8e30440d 100644 --- a/src/KqueueEventPoll.cc +++ b/src/KqueueEventPoll.cc @@ -43,6 +43,7 @@ #include "LogFactory.h" #include "Logger.h" #include "util.h" +#include "fmt.h" #ifdef KEVENT_UDATA_INTPTR_T # define PTR_TO_UDATA(X) (reinterpret_cast<intptr_t>(X)) @@ -52,8 +53,9 @@ namespace aria2 { -KqueueEventPoll::KSocketEntry::KSocketEntry(sock_t s): - SocketEntry<KCommandEvent, KADNSEvent>(s) {} +KqueueEventPoll::KSocketEntry::KSocketEntry(sock_t s) + : SocketEntry<KCommandEvent, KADNSEvent>(s) +{} int accumulateEvent(int events, const KqueueEventPoll::KEvent& event) { @@ -85,10 +87,9 @@ size_t KqueueEventPoll::KSocketEntry::getEvents return 2; } -KqueueEventPoll::KqueueEventPoll(): - kqEventsSize_(KQUEUE_EVENTS_MAX), - kqEvents_(new struct kevent[kqEventsSize_]), - logger_(LogFactory::getInstance()) +KqueueEventPoll::KqueueEventPoll() + : kqEventsSize_(KQUEUE_EVENTS_MAX), + kqEvents_(new struct kevent[kqEventsSize_]) { kqfd_ = kqueue(); } @@ -100,9 +101,10 @@ KqueueEventPoll::~KqueueEventPoll() while((r = close(kqfd_)) == -1 && errno == EINTR); int errNum = errno; if(r == -1) { - logger_->error("Error occurred while closing kqueue file descriptor" - " %d: %s", - kqfd_, util::safeStrerror(errNum).c_str()); + A2_LOG_ERROR(fmt("Error occurred while closing kqueue file descriptor" + " %d: %s", + kqfd_, + util::safeStrerror(errNum).c_str())); } } delete [] kqEvents_; @@ -192,10 +194,9 @@ bool KqueueEventPoll::addEvents r = kevent(kqfd_, changelist, n, changelist, 0, &zeroTimeout); int errNum = errno; if(r == -1) { - if(logger_->debug()) { - logger_->debug("Failed to add socket event %d:%s", - socket, util::safeStrerror(errNum).c_str()); - } + A2_LOG_DEBUG(fmt("Failed to add socket event %d:%s", + socket, + util::safeStrerror(errNum).c_str())); return false; } else { return true; @@ -236,18 +237,14 @@ bool KqueueEventPoll::deleteEvents(sock_t socket, socketEntries_.erase(i); } if(r == -1) { - if(logger_->debug()) { - logger_->debug("Failed to delete socket event:%s", - util::safeStrerror(errNum).c_str()); - } + A2_LOG_DEBUG(fmt("Failed to delete socket event:%s", + util::safeStrerror(errNum).c_str())); return false; } else { return true; } } else { - if(logger_->debug()) { - logger_->debug("Socket %d is not found in SocketEntries.", socket); - } + A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket)); return false; } } diff --git a/src/KqueueEventPoll.h b/src/KqueueEventPoll.h index cb9deeaf..37523efa 100644 --- a/src/KqueueEventPoll.h +++ b/src/KqueueEventPoll.h @@ -50,8 +50,6 @@ namespace aria2 { -class Logger; - class KqueueEventPoll : public EventPoll { private: class KSocketEntry; @@ -89,8 +87,6 @@ private: static const size_t KQUEUE_EVENTS_MAX = 1024; - Logger* logger_; - bool addEvents(sock_t socket, const KEvent& event); bool deleteEvents(sock_t socket, const KEvent& event); diff --git a/src/LibgnutlsTLSContext.cc b/src/LibgnutlsTLSContext.cc index f4ca2baf..6bd9e4ae 100644 --- a/src/LibgnutlsTLSContext.cc +++ b/src/LibgnutlsTLSContext.cc @@ -41,13 +41,14 @@ #include "LogFactory.h" #include "Logger.h" #include "StringFormat.h" +#include "fmt.h" #include "message.h" namespace aria2 { -TLSContext::TLSContext():certCred_(0), - peerVerificationEnabled_(false), - logger_(LogFactory::getInstance()) +TLSContext::TLSContext() + : certCred_(0), + peerVerificationEnabled_(false) { int r = gnutls_certificate_allocate_credentials(&certCred_); if(r == GNUTLS_E_SUCCESS) { @@ -56,8 +57,9 @@ TLSContext::TLSContext():certCred_(0), GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT); } else { good_ =false; - logger_->error("gnutls_certificate_allocate_credentials() failed." - " Cause: %s", gnutls_strerror(r)); + A2_LOG_ERROR(fmt("gnutls_certificate_allocate_credentials() failed." + " Cause: %s", + gnutls_strerror(r))); } } @@ -86,14 +88,14 @@ bool TLSContext::addClientKeyFile(const std::string& certfile, keyfile.c_str(), GNUTLS_X509_FMT_PEM); if(ret == GNUTLS_E_SUCCESS) { - logger_->info("Client Key File(cert=%s, key=%s) were successfully added.", - certfile.c_str(), keyfile.c_str()); + A2_LOG_INFO(fmt("Client Key File(cert=%s, key=%s) were successfully added.", + certfile.c_str(), keyfile.c_str())); return true; } else { - logger_->error("Failed to load client certificate from %s and" - " private key from %s. Cause: %s", - certfile.c_str(), keyfile.c_str(), - gnutls_strerror(ret)); + A2_LOG_ERROR(fmt("Failed to load client certificate from %s and" + " private key from %s. Cause: %s", + certfile.c_str(), keyfile.c_str(), + gnutls_strerror(ret))); return false; } } @@ -104,11 +106,11 @@ bool TLSContext::addTrustedCACertFile(const std::string& certfile) certfile.c_str(), GNUTLS_X509_FMT_PEM); if(ret < 0) { - logger_->error(MSG_LOADING_TRUSTED_CA_CERT_FAILED, - certfile.c_str(), gnutls_strerror(ret)); + A2_LOG_ERROR(fmt(MSG_LOADING_TRUSTED_CA_CERT_FAILED, + certfile.c_str(), gnutls_strerror(ret))); return false; } else { - logger_->info("%d certificate(s) were imported.", ret); + A2_LOG_INFO(fmt("%d certificate(s) were imported.", ret)); return true; } } diff --git a/src/LibgnutlsTLSContext.h b/src/LibgnutlsTLSContext.h index e3da322a..dd29cc69 100644 --- a/src/LibgnutlsTLSContext.h +++ b/src/LibgnutlsTLSContext.h @@ -45,8 +45,6 @@ namespace aria2 { -class Logger; - class TLSContext { private: gnutls_certificate_credentials_t certCred_; @@ -54,8 +52,6 @@ private: bool good_; bool peerVerificationEnabled_; - - Logger* logger_; public: TLSContext(); diff --git a/src/LibsslTLSContext.cc b/src/LibsslTLSContext.cc index 0bc84e8b..b3ff4d1f 100644 --- a/src/LibsslTLSContext.cc +++ b/src/LibsslTLSContext.cc @@ -39,21 +39,22 @@ #include "LogFactory.h" #include "Logger.h" #include "StringFormat.h" +#include "fmt.h" #include "message.h" namespace aria2 { -TLSContext::TLSContext():sslCtx_(0), - peerVerificationEnabled_(false), - logger_(LogFactory::getInstance()) +TLSContext::TLSContext() + : sslCtx_(0), + peerVerificationEnabled_(false) { sslCtx_ = SSL_CTX_new(SSLv23_client_method()); if(sslCtx_) { good_ = true; } else { good_ = false; - logger_->error("SSL_CTX_new() failed. Cause: %s", - ERR_error_string(ERR_get_error(), 0)); + A2_LOG_ERROR(fmt("SSL_CTX_new() failed. Cause: %s", + ERR_error_string(ERR_get_error(), 0))); } SSL_CTX_set_mode(sslCtx_, SSL_MODE_AUTO_RETRY); } @@ -78,28 +79,32 @@ bool TLSContext::addClientKeyFile(const std::string& certfile, { if(SSL_CTX_use_PrivateKey_file(sslCtx_, keyfile.c_str(), SSL_FILETYPE_PEM) != 1) { - logger_->error("Failed to load client private key from %s. Cause: %s", - keyfile.c_str(), ERR_error_string(ERR_get_error(), 0)); + A2_LOG_ERROR(fmt("Failed to load client private key from %s. Cause: %s", + keyfile.c_str(), + ERR_error_string(ERR_get_error(), 0))); return false; } if(SSL_CTX_use_certificate_chain_file(sslCtx_, certfile.c_str()) != 1) { - logger_->error("Failed to load client certificate from %s. Cause: %s", - certfile.c_str(), ERR_error_string(ERR_get_error(), 0)); + A2_LOG_ERROR(fmt("Failed to load client certificate from %s. Cause: %s", + certfile.c_str(), + ERR_error_string(ERR_get_error(), 0))); return false; } - logger_->info("Client Key File(cert=%s, key=%s) were successfully added.", - certfile.c_str(), keyfile.c_str()); + A2_LOG_INFO(fmt("Client Key File(cert=%s, key=%s) were successfully added.", + certfile.c_str(), + keyfile.c_str())); return true; } bool TLSContext::addTrustedCACertFile(const std::string& certfile) { if(SSL_CTX_load_verify_locations(sslCtx_, certfile.c_str(), 0) != 1) { - logger_->error(MSG_LOADING_TRUSTED_CA_CERT_FAILED, - certfile.c_str(), ERR_error_string(ERR_get_error(), 0)); + A2_LOG_ERROR(fmt(MSG_LOADING_TRUSTED_CA_CERT_FAILED, + certfile.c_str(), + ERR_error_string(ERR_get_error(), 0))); return false; } else { - logger_->info("Trusted CA certificates were successfully added."); + A2_LOG_INFO("Trusted CA certificates were successfully added."); return true; } } diff --git a/src/LibsslTLSContext.h b/src/LibsslTLSContext.h index 5262b7e9..66f361bb 100644 --- a/src/LibsslTLSContext.h +++ b/src/LibsslTLSContext.h @@ -45,8 +45,6 @@ namespace aria2 { -class Logger; - class TLSContext { private: SSL_CTX* sslCtx_; @@ -54,8 +52,6 @@ private: bool good_; bool peerVerificationEnabled_; - - Logger* logger_; public: TLSContext(); diff --git a/src/LogFactory.cc b/src/LogFactory.cc index d4008336..7df7623c 100644 --- a/src/LogFactory.cc +++ b/src/LogFactory.cc @@ -33,7 +33,6 @@ */ /* copyright --> */ #include "LogFactory.h" -#include "SimpleLogFormatter.h" #include "a2io.h" #include "prefs.h" #include "RecoverableException.h" @@ -71,7 +70,6 @@ void LogFactory::reconfigure() Logger* LogFactory::getInstance() { if(!logger_) { Logger* slogger = new Logger(); - slogger->setLogFormatter(new SimpleLogFormatter()); try { openLogger(slogger); } catch(RecoverableException& e) { diff --git a/src/LogFactory.h b/src/LogFactory.h index 09a9942b..371a9dde 100644 --- a/src/LogFactory.h +++ b/src/LogFactory.h @@ -46,6 +46,7 @@ namespace aria2 { class LogFactory { private: static std::string filename_; + // TODO consider SharedHandle static Logger* logger_; static bool consoleOutput_; static Logger::LEVEL logLevel_; diff --git a/src/Logger.cc b/src/Logger.cc index de60f246..c931faef 100644 --- a/src/Logger.cc +++ b/src/Logger.cc @@ -2,7 +2,7 @@ /* * aria2 - The high speed download utility * - * Copyright (C) 2006 Tatsuhiro Tsujikawa + * Copyright (C) 2010 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -35,176 +35,187 @@ #include "Logger.h" #include <cstring> +#include <iostream> #include "DlAbortEx.h" -#include "StringFormat.h" +#include "fmt.h" #include "message.h" -#include "LogFormatter.h" +#include "A2STR.h" +#include "a2time.h" namespace aria2 { -const std::string Logger::DEBUG_LABEL("DEBUG"); +namespace { +static const std::string DEBUG_LABEL("DEBUG"); -const std::string Logger::NOTICE_LABEL("NOTICE"); +static const std::string INFO_LABEL("INFO"); -const std::string Logger::WARN_LABEL("WARN"); +static const std::string NOTICE_LABEL("NOTICE"); -const std::string Logger::ERROR_LABEL("ERROR"); +static const std::string WARN_LABEL("WARN"); -const std::string Logger::INFO_LABEL("INFO"); +static const std::string ERROR_LABEL("ERROR"); +} // namespace -Logger::Logger(): - logFormatter_(0), logLevel_(Logger::A2_DEBUG), stdoutField_(0) {} +Logger::Logger() + : logLevel_(Logger::A2_DEBUG), + stdoutField_(0) +{} Logger::~Logger() { closeFile(); - delete logFormatter_; } void Logger::openFile(const std::string& filename) { file_.open(filename.c_str(), std::ios::app|std::ios::binary); if(!file_) { - throw DL_ABORT_EX - (StringFormat(EX_FILE_OPEN, filename.c_str(), "n/a").str()); + throw DL_ABORT_EX(fmt(EX_FILE_OPEN, filename.c_str(), "n/a")); } } void Logger::closeFile() { + std::cerr << "Closing log file" << std::endl; + // TODO Do we need file_.is_open()? if(file_.is_open()) { file_.close(); } } -#define WRITE_LOG(LEVEL, LEVEL_LABEL, MSG) \ - if(LEVEL >= logLevel_ && file_.is_open()) { \ - va_list ap; \ - va_start(ap, MSG); \ - writeLog(file_, LEVEL, LEVEL_LABEL, MSG, ap); \ - va_end(ap); \ - file_ << std::flush; \ - } \ - if(stdoutField_&LEVEL) { \ - std::cout << "\n"; \ - va_list ap; \ - va_start(ap, MSG); \ - writeLog(std::cout, LEVEL, LEVEL_LABEL, MSG, ap); \ - va_end(ap); \ - std::cout << std::flush; \ - } \ - -#define WRITE_LOG_EX(LEVEL, LEVEL_LABEL, MSG, EX) \ - if(LEVEL >= logLevel_ && file_.is_open()) { \ - va_list ap; \ - va_start(ap, EX); \ - writeLog(file_, LEVEL, LEVEL_LABEL, MSG, ap); \ - va_end(ap); \ - writeStackTrace(file_, LEVEL, LEVEL_LABEL, EX); \ - file_ << std::flush; \ - } \ - if(stdoutField_&LEVEL) { \ - std::cout << "\n"; \ - va_list ap; \ - va_start(ap, EX); \ - writeLog(std::cout, LEVEL, LEVEL_LABEL, MSG, ap); \ - va_end(ap); \ - writeStackTrace(std::cout, LEVEL, LEVEL_LABEL, EX); \ - std::cout << std::flush; \ - } \ - -void Logger::debug(const char* msg, ...) -{ - WRITE_LOG(A2_DEBUG, DEBUG_LABEL, msg); -} - -void Logger::debug(const char* msg, const Exception& ex, ...) -{ - WRITE_LOG_EX(A2_DEBUG, DEBUG_LABEL, msg, ex); -} - -void Logger::info(const char* msg, ...) -{ - WRITE_LOG(A2_INFO, INFO_LABEL, msg); -} - -void Logger::info(const char* msg, const Exception& ex, ...) -{ - WRITE_LOG_EX(A2_INFO, INFO_LABEL, msg, ex); -} - -void Logger::notice(const char* msg, ...) -{ - WRITE_LOG(A2_NOTICE, NOTICE_LABEL, msg); -} - -void Logger::notice(const char* msg, const Exception& ex, ...) -{ - WRITE_LOG_EX(A2_NOTICE, NOTICE_LABEL, msg, ex); -} - -void Logger::warn(const char* msg, ...) +void Logger::setStdoutLogLevel(Logger::LEVEL level, bool enabled) { - WRITE_LOG(A2_WARN, WARN_LABEL, msg); + if(enabled) { + stdoutField_ |= level; + } else { + stdoutField_ &= ~level; + } } -void Logger::warn(const char* msg, const Exception& ex, ...) +bool Logger::levelEnabled(LEVEL level) { - WRITE_LOG_EX(A2_WARN, WARN_LABEL, msg, ex); + return (level >= logLevel_ && file_.is_open()) || stdoutField_&level; } -void Logger::error(const char* msg, ...) +namespace { +const std::string& levelToString(Logger::LEVEL level) { - WRITE_LOG(A2_ERROR, ERROR_LABEL, msg); + switch(level) { + case Logger::A2_DEBUG: + return DEBUG_LABEL; + case Logger::A2_INFO: + return INFO_LABEL; + case Logger::A2_NOTICE: + return NOTICE_LABEL; + case Logger::A2_WARN: + return WARN_LABEL; + case Logger::A2_ERROR: + return ERROR_LABEL; + default: + return A2STR::NIL; + } } - -void Logger::error(const char* msg, const Exception& ex, ...) -{ - WRITE_LOG_EX(A2_ERROR, ERROR_LABEL, msg, ex); +} // namespace + +namespace { +void writeHeader +(std::ostream& o, Logger::LEVEL level, const char* sourceFile, int lineNum) +{ + struct timeval tv; + gettimeofday(&tv, 0); + char datestr[27]; // 'YYYY-MM-DD hh:mm:ss.uuuuuu'+'\0' = 27 bytes + struct tm tm; + //tv.tv_sec may not be of type time_t. + time_t timesec = tv.tv_sec; + localtime_r(×ec, &tm); + size_t dateLength = + strftime(datestr, sizeof(datestr), "%Y-%m-%d %H:%M:%S", &tm); + assert(dateLength <= (size_t)20); + snprintf(datestr+dateLength, + sizeof(datestr)-dateLength, + ".%06ld", tv.tv_usec); + o << datestr << " " << levelToString(level) << " - "; + if(sourceFile) { + o << "[" << sourceFile << ":" << lineNum << "] "; + } } +} // namespace -void Logger::setLogFormatter(LogFormatter* logFormatter) +namespace { +void writeStackTrace(std::ostream& o, const std::string& stackTrace) { - delete logFormatter_; - logFormatter_ = logFormatter; + o << stackTrace; } +} // namespace -void Logger::setStdoutLogLevel(Logger::LEVEL level, bool enabled) +namespace { +void writeLog +(std::ostream& o, + Logger::LEVEL level, + const char* sourceFile, + int lineNum, + const char* msg, + const std::string& trace, + bool toStream, + bool toConsole) { - if(enabled) { - stdoutField_ |= level; - } else { - stdoutField_ &= ~level; + if(toStream) { + writeHeader(o, level, sourceFile, lineNum); + o << msg << "\n"; + writeStackTrace(o, trace); + o << std::flush; + } + if(toConsole) { + std::cout << "\n"; + writeHeader(std::cout, level, 0, 0); + std::cout << msg << "\n"; + writeStackTrace(std::cout, trace); + std::cout << std::flush; } } +} // namespace -void Logger::writeLog -(std::ostream& o, LEVEL logLevel, const std::string& logLevelLabel, - const char* msg, va_list ap) +void Logger::log +(LEVEL level, + const char* sourceFile, + int lineNum, + const char* msg) { - if(logFormatter_) { - logFormatter_->writeLog(o, logLevel, logLevelLabel, msg, ap); - } + writeLog(file_, level, sourceFile, lineNum, msg, A2STR::NIL, + level >= logLevel_ && file_.is_open(), + stdoutField_&level); } -void Logger::writeStackTrace -(std::ostream& o, LEVEL logLevel, const std::string& logLevelLabel, - const Exception& ex) +void Logger::log +(LEVEL level, + const char* sourceFile, + int lineNum, + const std::string& msg) { - if(logFormatter_) { - logFormatter_->writeStackTrace(o, logLevel, logLevelLabel, ex); - } + log(level, sourceFile, lineNum, msg.c_str()); } -bool Logger::debug() +void Logger::log +(LEVEL level, + const char* sourceFile, + int lineNum, + const char* msg, + const Exception& ex) { - return levelEnabled(A2_DEBUG); + writeLog(file_, level, sourceFile, lineNum, msg, ex.stackTrace(), + level >= logLevel_ && file_.is_open(), + stdoutField_&level); } -bool Logger::info() +void Logger::log +(LEVEL level, + const char* sourceFile, + int lineNum, + const std::string& msg, + const Exception& ex) { - return levelEnabled(A2_INFO); + log(level, sourceFile, lineNum, msg.c_str(), ex); } } // namespace aria2 diff --git a/src/Logger.h b/src/Logger.h index af032453..6dee4851 100644 --- a/src/Logger.h +++ b/src/Logger.h @@ -2,7 +2,7 @@ /* * aria2 - The high speed download utility * - * Copyright (C) 2006 Tatsuhiro Tsujikawa + * Copyright (C) 2010 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -37,15 +37,12 @@ #include "common.h" -#include <cstdarg> #include <string> #include <fstream> -#include <iostream> namespace aria2 { class Exception; -class LogFormatter; class Logger { public: @@ -56,78 +53,45 @@ public: A2_WARN = 1 << 3, A2_ERROR = 1 << 4, }; - - static const std::string DEBUG_LABEL; - - static const std::string NOTICE_LABEL; - - static const std::string WARN_LABEL; - - static const std::string ERROR_LABEL; - - static const std::string INFO_LABEL; private: - LogFormatter* logFormatter_; - LEVEL logLevel_; - std::ofstream file_; - - int stdoutField_; - - bool levelEnabled(LEVEL level) - { - return (level >= logLevel_ && file_.is_open()) || stdoutField_&level; - } - - void writeLog - (std::ostream& o, LEVEL logLevel, const std::string& logLevelLabel, - const char* msg, va_list ap); - - void writeStackTrace - (std::ostream& o, LEVEL logLevel, const std::string& logLevelLabel, - const Exception& ex); + int stdoutField_; public: Logger(); - virtual ~Logger(); - - void debug(const char* msg, ...) - __attribute__ ((format (printf, 2, 3))); - - void debug(const char* msg, const Exception& ex, ...) - __attribute__ ((format (printf, 2, 4))); - - void info(const char* msg, ...) - __attribute__ ((format (printf, 2, 3))); - - void info(const char* msg, const Exception& ex, ...) - __attribute__ ((format (printf, 2, 4))); - - void notice(const char* msg, ...) - __attribute__ ((format (printf, 2, 3))); - - void notice(const char* msg, const Exception& ex, ...) - __attribute__ ((format (printf, 2, 4))); - - void warn(const char* msg, ...) - __attribute__ ((format (printf, 2, 3))); - - void warn(const char* msg, const Exception& ex, ...) - __attribute__ ((format (printf, 2, 4))); - - void error(const char* msg, ...) - __attribute__ ((format (printf, 2, 3))); + ~Logger(); + + void log + (LEVEL level, + const char* sourceFile, + int lineNum, + const char* msg); + + void log + (LEVEL level, + const char* sourceFile, + int lineNum, + const std::string& msg); + + void log + (LEVEL level, + const char* sourceFile, + int lineNum, + const char* msg, + const Exception& ex); - void error(const char* msg, const Exception& ex, ...) - __attribute__ ((format (printf, 2, 4))); + void log + (LEVEL level, + const char* sourceFile, + int lineNum, + const std::string& msg, + const Exception& ex); void openFile(const std::string& filename); void closeFile(); - void setLogFormatter(LogFormatter* logFormatter); - void setLogLevel(LEVEL level) { logLevel_ = level; @@ -137,11 +101,73 @@ public: // Returns true if this logger actually writes debug log message to // either file or stdout. - bool debug(); - - bool info(); + bool levelEnabled(LEVEL level); }; +#define A2_LOG_DEBUG_ENABLED \ + aria2::LogFactory::getInstance()->levelEnabled(Logger::A2_DEBUG) + +#define A2_LOG_DEBUG(msg) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_DEBUG)) \ + logger->log(Logger::A2_DEBUG, __FILE__, __LINE__, msg); \ + } +#define A2_LOG_DEBUG_EX(msg, ex) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_DEBUG)) \ + logger->log(Logger::A2_DEBUG, __FILE__, __LINE__, msg, ex); \ + } +#define A2_LOG_INFO(msg) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_INFO)) \ + logger->log(Logger::A2_INFO, __FILE__, __LINE__, msg); \ + } +#define A2_LOG_INFO_EX(msg, ex) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_INFO)) \ + logger->log(Logger::A2_INFO, __FILE__, __LINE__, msg, ex); \ + } +#define A2_LOG_NOTICE(msg) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_NOTICE)) \ + logger->log(Logger::A2_NOTICE, __FILE__, __LINE__, msg); \ + } +#define A2_LOG_NOTICE_EX(msg, ex) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_NOTICE)) \ + logger->log(Logger::A2_NOTICE, __FILE__, __LINE__, msg, ex); \ + } +#define A2_LOG_WARN(msg) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_WARN)) \ + logger->log(Logger::A2_WARN, __FILE__, __LINE__, msg); \ + } +#define A2_LOG_WARN_EX(msg, ex) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_WARN)) \ + logger->log(Logger::A2_WARN, __FILE__, __LINE__, msg, ex); \ + } +#define A2_LOG_ERROR(msg) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_ERROR)) \ + logger->log(Logger::A2_ERROR, __FILE__, __LINE__, msg); \ + } +#define A2_LOG_ERROR_EX(msg, ex) \ + { \ + aria2::Logger* logger = aria2::LogFactory::getInstance(); \ + if(logger->levelEnabled(Logger::A2_ERROR)) \ + logger->log(Logger::A2_ERROR, __FILE__, __LINE__, msg, ex); \ + } + } // namespace aria2 #endif // D_LOGGER_H diff --git a/src/LpdDispatchMessageCommand.cc b/src/LpdDispatchMessageCommand.cc index a6044a12..00c74808 100644 --- a/src/LpdDispatchMessageCommand.cc +++ b/src/LpdDispatchMessageCommand.cc @@ -37,20 +37,23 @@ #include "DownloadEngine.h" #include "BtRuntime.h" #include "Logger.h" +#include "LogFactory.h" #include "RecoverableException.h" #include "SocketCore.h" #include "util.h" +#include "fmt.h" namespace aria2 { LpdDispatchMessageCommand::LpdDispatchMessageCommand (cuid_t cuid, const SharedHandle<LpdMessageDispatcher>& dispatcher, - DownloadEngine* e): - Command(cuid), - dispatcher_(dispatcher), - e_(e), - tryCount_(0) {} + DownloadEngine* e) + : Command(cuid), + dispatcher_(dispatcher), + e_(e), + tryCount_(0) +{} LpdDispatchMessageCommand::~LpdDispatchMessageCommand() {} @@ -61,25 +64,25 @@ bool LpdDispatchMessageCommand::execute() } if(dispatcher_->isAnnounceReady()) { try { - getLogger()->info("Dispatching LPD message for infohash=%s", - util::toHex(dispatcher_->getInfoHash()).c_str()); + A2_LOG_INFO(fmt("Dispatching LPD message for infohash=%s", + util::toHex(dispatcher_->getInfoHash()).c_str())); if(dispatcher_->sendMessage()) { - getLogger()->info("Sending LPD message is complete."); + A2_LOG_INFO("Sending LPD message is complete."); dispatcher_->resetAnnounceTimer(); tryCount_ = 0; } else { ++tryCount_; if(tryCount_ >= 5) { - getLogger()->info("Sending LPD message %u times but all failed.", - tryCount_); + A2_LOG_INFO(fmt("Sending LPD message %u times but all failed.", + tryCount_)); dispatcher_->resetAnnounceTimer(); tryCount_ = 0; } else { - getLogger()->info("Could not send LPD message, retry shortly."); + A2_LOG_INFO("Could not send LPD message, retry shortly."); } } } catch(RecoverableException& e) { - getLogger()->info("Failed to send LPD message.", e); + A2_LOG_INFO_EX("Failed to send LPD message.", e); dispatcher_->resetAnnounceTimer(); tryCount_ = 0; } diff --git a/src/LpdMessageDispatcher.cc b/src/LpdMessageDispatcher.cc index 629e5dff..ba2bbdf7 100644 --- a/src/LpdMessageDispatcher.cc +++ b/src/LpdMessageDispatcher.cc @@ -39,22 +39,25 @@ #include "BtConstants.h" #include "RecoverableException.h" #include "wallclock.h" +#include "fmt.h" namespace aria2 { LpdMessageDispatcher::LpdMessageDispatcher -(const std::string& infoHash, uint16_t port, - const std::string& multicastAddress, uint16_t multicastPort, - time_t interval): - infoHash_(infoHash), - port_(port), - multicastAddress_(multicastAddress), - multicastPort_(multicastPort), - timer_(0), - interval_(interval), - request_(bittorrent::createLpdRequest(multicastAddress_, multicastPort_, - infoHash_, port_)), - logger_(LogFactory::getInstance()) {} +(const std::string& infoHash, + uint16_t port, + const std::string& multicastAddress, + uint16_t multicastPort, + time_t interval) + : infoHash_(infoHash), + port_(port), + multicastAddress_(multicastAddress), + multicastPort_(multicastPort), + timer_(0), + interval_(interval), + request_(bittorrent::createLpdRequest(multicastAddress_, multicastPort_, + infoHash_, port_)) +{} LpdMessageDispatcher::~LpdMessageDispatcher() {} @@ -64,23 +67,18 @@ bool LpdMessageDispatcher::init(const std::string& localAddr, try { socket_.reset(new SocketCore(SOCK_DGRAM)); socket_->create(AF_INET); - if(logger_->debug()) { - logger_->debug("Setting multicast outgoing interface=%s", - localAddr.c_str()); - } + A2_LOG_DEBUG(fmt("Setting multicast outgoing interface=%s", + localAddr.c_str())); socket_->setMulticastInterface(localAddr); - if(logger_->debug()) { - logger_->debug("Setting multicast ttl=%u",static_cast<unsigned int>(ttl)); - } + A2_LOG_DEBUG(fmt("Setting multicast ttl=%u", + static_cast<unsigned int>(ttl))); socket_->setMulticastTtl(ttl); - if(logger_->debug()) { - logger_->debug("Setting multicast loop=%u", - static_cast<unsigned int>(loop)); - } + A2_LOG_DEBUG(fmt("Setting multicast loop=%u", + static_cast<unsigned int>(loop))); socket_->setMulticastLoop(loop); return true; } catch(RecoverableException& e) { - logger_->error("Failed to initialize LpdMessageDispatcher.", e); + A2_LOG_ERROR_EX("Failed to initialize LpdMessageDispatcher.", e); } return false; } diff --git a/src/LpdMessageDispatcher.h b/src/LpdMessageDispatcher.h index edfee452..e4685416 100644 --- a/src/LpdMessageDispatcher.h +++ b/src/LpdMessageDispatcher.h @@ -43,7 +43,6 @@ namespace aria2 { class SocketCore; -class Logger; class LpdMessageDispatcher { private: @@ -55,7 +54,6 @@ private: Timer timer_; time_t interval_; std::string request_; - Logger* logger_; public: LpdMessageDispatcher (const std::string& infoHash, uint16_t port, diff --git a/src/LpdMessageReceiver.cc b/src/LpdMessageReceiver.cc index 1c6db0a0..f5fd290c 100644 --- a/src/LpdMessageReceiver.cc +++ b/src/LpdMessageReceiver.cc @@ -40,14 +40,15 @@ #include "LpdMessage.h" #include "RecoverableException.h" #include "Peer.h" +#include "fmt.h" namespace aria2 { LpdMessageReceiver::LpdMessageReceiver -(const std::string& multicastAddress, uint16_t multicastPort): - multicastAddress_(multicastAddress), - multicastPort_(multicastPort), - logger_(LogFactory::getInstance()) {} +(const std::string& multicastAddress, uint16_t multicastPort) + : multicastAddress_(multicastAddress), + multicastPort_(multicastPort) +{} LpdMessageReceiver::~LpdMessageReceiver() {} @@ -61,19 +62,17 @@ bool LpdMessageReceiver::init(const std::string& localAddr) #else // !__MINGW32__ socket_->bind(multicastAddress_, multicastPort_, AF_INET); #endif // !__MINGW32__ - if(logger_->debug()) { - logger_->debug("Joining multicast group. %s:%u, localAddr=%s", + A2_LOG_DEBUG(fmt("Joining multicast group. %s:%u, localAddr=%s", multicastAddress_.c_str(), multicastPort_, - localAddr.c_str()); - } + localAddr.c_str())); socket_->joinMulticastGroup(multicastAddress_, multicastPort_, localAddr); socket_->setNonBlockingMode(); localAddress_ = localAddr; - logger_->info("Listening multicast group (%s:%u) packet", - multicastAddress_.c_str(), multicastPort_); + A2_LOG_INFO(fmt("Listening multicast group (%s:%u) packet", + multicastAddress_.c_str(), multicastPort_)); return true; } catch(RecoverableException& e) { - logger_->error("Failed to initialize LPD message receiver.", e); + A2_LOG_ERROR_EX("Failed to initialize LPD message receiver.", e); } return false; } @@ -97,13 +96,15 @@ SharedHandle<LpdMessage> LpdMessageReceiver::receiveMessage() SharedHandle<HttpHeader> header = proc.getHttpRequestHeader(); std::string infoHashString = header->getFirst("Infohash"); uint16_t port = header->getFirstAsUInt("Port"); - logger_->info("LPD message received infohash=%s, port=%u from %s", - infoHashString.c_str(), port, peerAddr.first.c_str()); + A2_LOG_INFO(fmt("LPD message received infohash=%s, port=%u from %s", + infoHashString.c_str(), + port, + peerAddr.first.c_str())); std::string infoHash; if(infoHashString.size() != 40 || (infoHash = util::fromHex(infoHashString)).empty() || port == 0) { - logger_->info("LPD bad request. infohash=%s", infoHashString.c_str()); + A2_LOG_INFO(fmt("LPD bad request. infohash=%s", infoHashString.c_str())); msg.reset(new LpdMessage()); return msg; } @@ -114,7 +115,7 @@ SharedHandle<LpdMessage> LpdMessageReceiver::receiveMessage() msg.reset(new LpdMessage(peer, infoHash)); return msg; } catch(RecoverableException& e) { - logger_->info("Failed to receive LPD message.", e); + A2_LOG_INFO_EX("Failed to receive LPD message.", e); msg.reset(new LpdMessage()); return msg; } diff --git a/src/LpdMessageReceiver.h b/src/LpdMessageReceiver.h index 2cff5700..757d9800 100644 --- a/src/LpdMessageReceiver.h +++ b/src/LpdMessageReceiver.h @@ -42,7 +42,6 @@ namespace aria2 { class SocketCore; -class Logger; class LpdMessage; class LpdMessageReceiver { @@ -51,7 +50,6 @@ private: std::string multicastAddress_; uint16_t multicastPort_; std::string localAddress_; - Logger* logger_; public: // Currently only IPv4 multicastAddresses are supported. LpdMessageReceiver diff --git a/src/LpdReceiveMessageCommand.cc b/src/LpdReceiveMessageCommand.cc index 594fa16a..741c6033 100644 --- a/src/LpdReceiveMessageCommand.cc +++ b/src/LpdReceiveMessageCommand.cc @@ -43,9 +43,11 @@ #include "RequestGroup.h" #include "BtRegistry.h" #include "Logger.h" +#include "LogFactory.h" #include "LpdMessage.h" #include "bittorrent_helper.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -54,8 +56,12 @@ unsigned int LpdReceiveMessageCommand::numInstance_ = 0; LpdReceiveMessageCommand* LpdReceiveMessageCommand::instance_ = 0; LpdReceiveMessageCommand::LpdReceiveMessageCommand -(cuid_t cuid, const SharedHandle<LpdMessageReceiver>& receiver, - DownloadEngine* e):Command(cuid), receiver_(receiver), e_(e) +(cuid_t cuid, + const SharedHandle<LpdMessageReceiver>& receiver, + DownloadEngine* e) + : Command(cuid), + receiver_(receiver), + e_(e) { e_->addSocketForReadCheck(receiver_->getSocket(), this); ++numInstance_; @@ -88,17 +94,12 @@ bool LpdReceiveMessageCommand::execute() SharedHandle<DownloadContext> dctx = reg->getDownloadContext(m->getInfoHash()); if(!dctx) { - if(getLogger()->debug()) { - getLogger()->debug("Download Context is null for infohash=%s.", - util::toHex(m->getInfoHash()).c_str()); - } + A2_LOG_DEBUG(fmt("Download Context is null for infohash=%s.", + util::toHex(m->getInfoHash()).c_str())); continue; } if(bittorrent::getTorrentAttrs(dctx)->privateTorrent) { - if(getLogger()->debug()) { - getLogger()->debug - ("Ignore LPD message because the torrent is private."); - } + A2_LOG_DEBUG("Ignore LPD message because the torrent is private."); continue; } RequestGroup* group = dctx->getOwnerRequestGroup(); @@ -109,17 +110,13 @@ bool LpdReceiveMessageCommand::execute() assert(peerStorage); SharedHandle<Peer> peer = m->getPeer(); if(peerStorage->addPeer(peer)) { - if(getLogger()->debug()) { - getLogger()->debug("LPD peer %s:%u local=%d added.", - peer->getIPAddress().c_str(), peer->getPort(), - peer->isLocalPeer()?1:0); - } + A2_LOG_DEBUG(fmt("LPD peer %s:%u local=%d added.", + peer->getIPAddress().c_str(), peer->getPort(), + peer->isLocalPeer()?1:0)); } else { - if(getLogger()->debug()) { - getLogger()->debug("LPD peer %s:%u local=%d not added.", - peer->getIPAddress().c_str(), peer->getPort(), - peer->isLocalPeer()?1:0); - } + A2_LOG_DEBUG(fmt("LPD peer %s:%u local=%d not added.", + peer->getIPAddress().c_str(), peer->getPort(), + peer->isLocalPeer()?1:0)); } } e_->addCommand(this); diff --git a/src/MSEHandshake.cc b/src/MSEHandshake.cc index 0ae9c6b5..5eb35b37 100644 --- a/src/MSEHandshake.cc +++ b/src/MSEHandshake.cc @@ -55,6 +55,7 @@ #include "prefs.h" #include "Option.h" #include "StringFormat.h" +#include "fmt.h" #include "bittorrent_helper.h" namespace aria2 { @@ -65,23 +66,23 @@ const unsigned char* MSEHandshake::GENERATOR = reinterpret_cast<const unsigned c const unsigned char MSEHandshake::VC[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; -MSEHandshake::MSEHandshake(cuid_t cuid, - const SocketHandle& socket, - const Option* op): - cuid_(cuid), - socket_(socket), - option_(op), - logger_(LogFactory::getInstance()), - rbufLength_(0), - socketBuffer_(socket), - negotiatedCryptoType_(CRYPTO_NONE), - dh_(0), - initiator_(true), - markerIndex_(0), - padLength_(0), - iaLength_(0), - ia_(0), - sha1_(MessageDigest::sha1()) +MSEHandshake::MSEHandshake +(cuid_t cuid, + const SocketHandle& socket, + const Option* op) + : cuid_(cuid), + socket_(socket), + option_(op), + rbufLength_(0), + socketBuffer_(socket), + negotiatedCryptoType_(CRYPTO_NONE), + dh_(0), + initiator_(true), + markerIndex_(0), + padLength_(0), + iaLength_(0), + ia_(0), + sha1_(MessageDigest::sha1()) {} MSEHandshake::~MSEHandshake() @@ -106,16 +107,12 @@ MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType() } if(rbuf_[0] == BtHandshakeMessage::PSTR_LENGTH && memcmp(BtHandshakeMessage::BT_PSTR, rbuf_+1, 19) == 0) { - if(logger_->debug()) { - logger_->debug("CUID#%s - This is legacy BitTorrent handshake.", - util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - This is legacy BitTorrent handshake.", + util::itos(cuid_).c_str())); return HANDSHAKE_LEGACY; } else { - if(logger_->debug()) { - logger_->debug("CUID#%s - This may be encrypted BitTorrent handshake.", - util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - This may be encrypted BitTorrent handshake.", + util::itos(cuid_).c_str())); return HANDSHAKE_ENCRYPTED; } } @@ -126,19 +123,15 @@ void MSEHandshake::initEncryptionFacility(bool initiator) dh_ = new DHKeyExchange(); dh_->init(PRIME, PRIME_BITS, GENERATOR, 160); dh_->generatePublicKey(); - if(logger_->debug()) { - logger_->debug("CUID#%s - DH initialized.", util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - DH initialized.", util::itos(cuid_).c_str())); initiator_ = initiator; } bool MSEHandshake::sendPublicKey() { if(socketBuffer_.sendBufferIsEmpty()) { - if(logger_->debug()) { - logger_->debug("CUID#%s - Sending public key.", - util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Sending public key.", + util::itos(cuid_).c_str())); unsigned char buffer[KEY_LENGTH+MAX_PAD_LENGTH]; dh_->getPublicKey(buffer, KEY_LENGTH); @@ -157,9 +150,8 @@ bool MSEHandshake::receivePublicKey() if(r > receiveNBytes(r)) { return false; } - if(logger_->debug()) { - logger_->debug("CUID#%s - public key received.", util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - public key received.", + util::itos(cuid_).c_str())); // TODO handle exception. in catch, resbufLength = 0; dh_->computeSecret(secret_, sizeof(secret_), rbuf_, rbufLength_); // reset rbufLength_ @@ -263,10 +255,8 @@ uint16_t MSEHandshake::decodeLength16(const unsigned char* buffer) bool MSEHandshake::sendInitiatorStep2() { if(socketBuffer_.sendBufferIsEmpty()) { - if(logger_->debug()) { - logger_->debug("CUID#%s - Sending negotiation step2.", - util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Sending negotiation step2.", + util::itos(cuid_).c_str())); unsigned char md[20]; createReq1Hash(md); socketBuffer_.pushStr(std::string(&md[0], &md[sizeof(md)])); @@ -352,11 +342,9 @@ bool MSEHandshake::findInitiatorVCMarker() size_t toRead = markerIndex_+VC_LENGTH-rbufLength_; socket_->readData(rbuf_+rbufLength_, toRead); rbufLength_ += toRead; - if(logger_->debug()) { - logger_->debug("CUID#%s - VC marker found at %lu", + A2_LOG_DEBUG(fmt("CUID#%s - VC marker found at %lu", util::itos(cuid_).c_str(), - static_cast<unsigned long>(markerIndex_)); - } + static_cast<unsigned long>(markerIndex_))); verifyVC(rbuf_+markerIndex_); // reset rbufLength_ rbufLength_ = 0; @@ -377,17 +365,13 @@ bool MSEHandshake::receiveInitiatorCryptoSelectAndPadDLength() rbufptr, sizeof(cryptoSelect)); if(cryptoSelect[3]&CRYPTO_PLAIN_TEXT && option_->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) { - if(logger_->debug()) { - logger_->debug("CUID#%s - peer prefers plaintext.", - util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - peer prefers plaintext.", + util::itos(cuid_).c_str())); negotiatedCryptoType_ = CRYPTO_PLAIN_TEXT; } if(cryptoSelect[3]&CRYPTO_ARC4) { - if(logger_->debug()) { - logger_->debug("CUID#%s - peer prefers ARC4", - util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - peer prefers ARC4", + util::itos(cuid_).c_str())); negotiatedCryptoType_ = CRYPTO_ARC4; } if(negotiatedCryptoType_ == CRYPTO_NONE) { @@ -454,11 +438,9 @@ bool MSEHandshake::findReceiverHashMarker() size_t toRead = markerIndex_+20-rbufLength_; socket_->readData(rbuf_+rbufLength_, toRead); rbufLength_ += toRead; - if(logger_->debug()) { - logger_->debug("CUID#%s - Hash marker found at %lu.", + A2_LOG_DEBUG(fmt("CUID#%s - Hash marker found at %lu.", util::itos(cuid_).c_str(), - static_cast<unsigned long>(markerIndex_)); - } + static_cast<unsigned long>(markerIndex_))); verifyReq1Hash(rbuf_+markerIndex_); // reset rbufLength_ rbufLength_ = 0; @@ -483,11 +465,9 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength const unsigned char* infohash = bittorrent::getInfoHash(*i); createReq23Hash(md, infohash); if(memcmp(md, rbufptr, sizeof(md)) == 0) { - if(logger_->debug()) { - logger_->debug("CUID#%s - info hash found: %s", + A2_LOG_DEBUG(fmt("CUID#%s - info hash found: %s", util::itos(cuid_).c_str(), - util::toHex(infohash, INFO_HASH_LENGTH).c_str()); - } + util::toHex(infohash, INFO_HASH_LENGTH).c_str())); downloadContext = *i; break; } @@ -509,16 +489,12 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength // For now, choose ARC4. if(cryptoProvide[3]&CRYPTO_PLAIN_TEXT && option_->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) { - if(logger_->debug()) { - logger_->debug("CUID#%s - peer provides plaintext.", - util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - peer provides plaintext.", + util::itos(cuid_).c_str())); negotiatedCryptoType_ = CRYPTO_PLAIN_TEXT; } else if(cryptoProvide[3]&CRYPTO_ARC4) { - if(logger_->debug()) { - logger_->debug("CUID#%s - peer provides ARC4.", - util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - peer provides ARC4.", + util::itos(cuid_).c_str())); negotiatedCryptoType_ = CRYPTO_ARC4; } if(negotiatedCryptoType_ == CRYPTO_NONE) { @@ -543,10 +519,8 @@ bool MSEHandshake::receiveReceiverIALength() return false; } iaLength_ = decodeLength16(rbuf_); - if(logger_->debug()) { - logger_->debug("CUID#%s - len(IA)=%u.", - util::itos(cuid_).c_str(), iaLength_); - } + A2_LOG_DEBUG(fmt("CUID#%s - len(IA)=%u.", + util::itos(cuid_).c_str(), iaLength_)); // reset rbufLength_ rbufLength_ = 0; return true; @@ -564,9 +538,7 @@ bool MSEHandshake::receiveReceiverIA() delete [] ia_; ia_ = new unsigned char[iaLength_]; decryptor_->decrypt(ia_, iaLength_, rbuf_, iaLength_); - if(logger_->debug()) { - logger_->debug("CUID#%s - IA received.", util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - IA received.", util::itos(cuid_).c_str())); // reset rbufLength_ rbufLength_ = 0; return true; @@ -605,15 +577,11 @@ bool MSEHandshake::sendReceiverStep2() uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf, const char* padName) { - if(logger_->debug()) { - logger_->debug("CUID#%s - Verifying Pad length for %s", - util::itos(cuid_).c_str(), padName); - } + A2_LOG_DEBUG(fmt("CUID#%s - Verifying Pad length for %s", + util::itos(cuid_).c_str(), padName)); uint16_t padLength = decodeLength16(padlenbuf); - if(logger_->debug()) { - logger_->debug("CUID#%s - len(%s)=%u", - util::itos(cuid_).c_str(), padName, padLength); - } + A2_LOG_DEBUG(fmt("CUID#%s - len(%s)=%u", + util::itos(cuid_).c_str(), padName, padLength)); if(padLength > 512) { throw DL_ABORT_EX (StringFormat("Too large %s length: %u", padName, padLength).str()); @@ -623,9 +591,7 @@ uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf, const cha void MSEHandshake::verifyVC(const unsigned char* vcbuf) { - if(logger_->debug()) { - logger_->debug("CUID#%s - Verifying VC.", util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Verifying VC.", util::itos(cuid_).c_str())); unsigned char vc[VC_LENGTH]; decryptor_->decrypt(vc, sizeof(vc), vcbuf, sizeof(vc)); if(memcmp(VC, vc, sizeof(VC)) != 0) { @@ -636,9 +602,7 @@ void MSEHandshake::verifyVC(const unsigned char* vcbuf) void MSEHandshake::verifyReq1Hash(const unsigned char* req1buf) { - if(logger_->debug()) { - logger_->debug("CUID#%s - Verifying req hash.", util::itos(cuid_).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Verifying req hash.", util::itos(cuid_).c_str())); unsigned char md[20]; createReq1Hash(md); if(memcmp(md, req1buf, sizeof(md)) != 0) { diff --git a/src/MSEHandshake.h b/src/MSEHandshake.h index 7cb988c9..4e22d407 100644 --- a/src/MSEHandshake.h +++ b/src/MSEHandshake.h @@ -47,7 +47,6 @@ namespace aria2 { class Option; -class Logger; class SocketCore; class DHKeyExchange; class ARC4Encryptor; @@ -85,7 +84,6 @@ private: cuid_t cuid_; SharedHandle<SocketCore> socket_; const Option* option_; - Logger* logger_; unsigned char rbuf_[MAX_BUFFER_LENGTH]; size_t rbufLength_; diff --git a/src/Makefile.am b/src/Makefile.am index 84f16a77..bc172c8f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -40,8 +40,7 @@ SRCS = Socket.h\ DlRetryEx.cc DlRetryEx.h\ DownloadFailureException.cc DownloadFailureException.h\ Logger.cc Logger.h\ - LogFormatter.h\ - SimpleLogFormatter.cc SimpleLogFormatter.h\ + fmt.cc fmt.h\ DiskWriter.h\ DiskWriterFactory.h\ AbstractDiskWriter.cc AbstractDiskWriter.h\ diff --git a/src/Makefile.in b/src/Makefile.in index 3f399dc9..6ae33d66 100644 --- a/src/Makefile.in +++ b/src/Makefile.in @@ -351,10 +351,9 @@ am__libaria2c_a_SOURCES_DIST = Socket.h SocketCore.cc SocketCore.h \ FatalException.h RecoverableException.cc \ RecoverableException.h DlAbortEx.cc DlAbortEx.h DlRetryEx.cc \ DlRetryEx.h DownloadFailureException.cc \ - DownloadFailureException.h Logger.cc Logger.h LogFormatter.h \ - SimpleLogFormatter.cc SimpleLogFormatter.h DiskWriter.h \ - DiskWriterFactory.h AbstractDiskWriter.cc AbstractDiskWriter.h \ - DefaultDiskWriter.cc DefaultDiskWriter.h \ + DownloadFailureException.h Logger.cc Logger.h fmt.cc fmt.h \ + DiskWriter.h DiskWriterFactory.h AbstractDiskWriter.cc \ + AbstractDiskWriter.h DefaultDiskWriter.cc DefaultDiskWriter.h \ DefaultDiskWriterFactory.cc DefaultDiskWriterFactory.h File.cc \ File.h Option.cc Option.h Base64.cc Base64.h base32.cc \ base32.h LogFactory.cc LogFactory.h TimerA2.cc TimerA2.h \ @@ -882,13 +881,13 @@ am__objects_32 = SocketCore.$(OBJEXT) Command.$(OBJEXT) \ Request.$(OBJEXT) Exception.$(OBJEXT) FatalException.$(OBJEXT) \ RecoverableException.$(OBJEXT) DlAbortEx.$(OBJEXT) \ DlRetryEx.$(OBJEXT) DownloadFailureException.$(OBJEXT) \ - Logger.$(OBJEXT) SimpleLogFormatter.$(OBJEXT) \ - AbstractDiskWriter.$(OBJEXT) DefaultDiskWriter.$(OBJEXT) \ - DefaultDiskWriterFactory.$(OBJEXT) File.$(OBJEXT) \ - Option.$(OBJEXT) Base64.$(OBJEXT) base32.$(OBJEXT) \ - LogFactory.$(OBJEXT) TimerA2.$(OBJEXT) TimeA2.$(OBJEXT) \ - FeatureConfig.$(OBJEXT) DownloadEngineFactory.$(OBJEXT) \ - SpeedCalc.$(OBJEXT) PeerStat.$(OBJEXT) BitfieldMan.$(OBJEXT) \ + Logger.$(OBJEXT) fmt.$(OBJEXT) AbstractDiskWriter.$(OBJEXT) \ + DefaultDiskWriter.$(OBJEXT) DefaultDiskWriterFactory.$(OBJEXT) \ + File.$(OBJEXT) Option.$(OBJEXT) Base64.$(OBJEXT) \ + base32.$(OBJEXT) LogFactory.$(OBJEXT) TimerA2.$(OBJEXT) \ + TimeA2.$(OBJEXT) FeatureConfig.$(OBJEXT) \ + DownloadEngineFactory.$(OBJEXT) SpeedCalc.$(OBJEXT) \ + PeerStat.$(OBJEXT) BitfieldMan.$(OBJEXT) \ SimpleRandomizer.$(OBJEXT) HttpResponse.$(OBJEXT) \ HttpRequest.$(OBJEXT) Range.$(OBJEXT) \ AbstractProxyRequestCommand.$(OBJEXT) \ @@ -1199,10 +1198,9 @@ SRCS = Socket.h SocketCore.cc SocketCore.h BinaryStream.h Command.cc \ FatalException.h RecoverableException.cc \ RecoverableException.h DlAbortEx.cc DlAbortEx.h DlRetryEx.cc \ DlRetryEx.h DownloadFailureException.cc \ - DownloadFailureException.h Logger.cc Logger.h LogFormatter.h \ - SimpleLogFormatter.cc SimpleLogFormatter.h DiskWriter.h \ - DiskWriterFactory.h AbstractDiskWriter.cc AbstractDiskWriter.h \ - DefaultDiskWriter.cc DefaultDiskWriter.h \ + DownloadFailureException.h Logger.cc Logger.h fmt.cc fmt.h \ + DiskWriter.h DiskWriterFactory.h AbstractDiskWriter.cc \ + AbstractDiskWriter.h DefaultDiskWriter.cc DefaultDiskWriter.h \ DefaultDiskWriterFactory.cc DefaultDiskWriterFactory.h File.cc \ File.h Option.cc Option.h Base64.cc Base64.h base32.cc \ base32.h LogFactory.cc LogFactory.h TimerA2.cc TimerA2.h \ @@ -1719,7 +1717,6 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ShareRatioSeedCriteria.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Signature.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SimpleBtMessage.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SimpleLogFormatter.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SimpleRandomizer.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SingleFileAllocationIterator.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SinkStreamFilter.Po@am__quote@ @@ -1776,6 +1773,7 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cookie_helper.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/daemon.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/download_helper.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fmt.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gai_strerror.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getaddrinfo.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gettimeofday.Po@am__quote@ diff --git a/src/Metalink2RequestGroup.cc b/src/Metalink2RequestGroup.cc index 6687b2c8..1f610937 100644 --- a/src/Metalink2RequestGroup.cc +++ b/src/Metalink2RequestGroup.cc @@ -55,6 +55,7 @@ #include "A2STR.h" #include "a2functional.h" #include "download_helper.h" +#include "fmt.h" #ifdef ENABLE_BITTORRENT # include "BtDependency.h" # include "download_helper.h" @@ -66,8 +67,7 @@ namespace aria2 { -Metalink2RequestGroup::Metalink2RequestGroup(): - logger_(LogFactory::getInstance()) {} +Metalink2RequestGroup::Metalink2RequestGroup() {} namespace { class AccumulateNonP2PUri { @@ -148,7 +148,7 @@ Metalink2RequestGroup::createRequestGroup const SharedHandle<Option>& option) { if(entries.empty()) { - logger_->notice(EX_NO_RESULT_WITH_YOUR_PREFS); + A2_LOG_NOTICE(EX_NO_RESULT_WITH_YOUR_PREFS); return; } std::vector<int32_t> selectIndexes = @@ -197,7 +197,7 @@ Metalink2RequestGroup::createRequestGroup entryGroups.begin(), eoi = entryGroups.end(); itr != eoi; ++itr) { const std::string& metaurl = (*itr).first; const std::vector<SharedHandle<MetalinkEntry> >& mes = (*itr).second; - logger_->info("Processing metaurl group metaurl=%s", metaurl.c_str()); + A2_LOG_INFO(fmt("Processing metaurl group metaurl=%s", metaurl.c_str())); #ifdef ENABLE_BITTORRENT SharedHandle<RequestGroup> torrentRg; if(!metaurl.empty()) { @@ -233,7 +233,7 @@ Metalink2RequestGroup::createRequestGroup SharedHandle<DownloadContext> dctx; if(mes.size() == 1) { SharedHandle<MetalinkEntry> entry = mes[0]; - logger_->info(MSG_METALINK_QUEUEING, entry->getPath().c_str()); + A2_LOG_INFO(fmt(MSG_METALINK_QUEUEING, entry->getPath().c_str())); entry->reorderResourcesByPriority(); std::vector<std::string> uris; std::for_each(entry->resources.begin(), entry->resources.end(), @@ -286,9 +286,9 @@ Metalink2RequestGroup::createRequestGroup off_t offset = 0; for(std::vector<SharedHandle<MetalinkEntry> >::const_iterator i = mes.begin(), eoi = mes.end(); i != eoi; ++i) { - logger_->info("Metalink: Queueing %s for download as a member.", - (*i)->getPath().c_str()); - logger_->debug("originalName = %s", (*i)->metaurls[0]->name.c_str()); + A2_LOG_INFO(fmt("Metalink: Queueing %s for download as a member.", + (*i)->getPath().c_str())); + A2_LOG_DEBUG(fmt("originalName = %s", (*i)->metaurls[0]->name.c_str())); (*i)->reorderResourcesByPriority(); std::vector<std::string> uris; std::for_each((*i)->resources.begin(), (*i)->resources.end(), diff --git a/src/Metalink2RequestGroup.h b/src/Metalink2RequestGroup.h index e75ccc84..d303cd5f 100644 --- a/src/Metalink2RequestGroup.h +++ b/src/Metalink2RequestGroup.h @@ -43,15 +43,12 @@ namespace aria2 { class Option; -class Logger; class RequestGroup; class BinaryStream; class MetalinkEntry; class Metalink2RequestGroup { private: - Logger* logger_; - void createRequestGroup(std::vector<SharedHandle<RequestGroup> >& groups, const std::vector<SharedHandle<MetalinkEntry> >& entries, diff --git a/src/MetalinkPostDownloadHandler.cc b/src/MetalinkPostDownloadHandler.cc index 3b142bfe..c6c86ad7 100644 --- a/src/MetalinkPostDownloadHandler.cc +++ b/src/MetalinkPostDownloadHandler.cc @@ -36,6 +36,7 @@ #include "RequestGroup.h" #include "Metalink2RequestGroup.h" #include "Logger.h" +#include "LogFactory.h" #include "DiskAdaptor.h" #include "PieceStorage.h" #include "DownloadHandlerConstants.h" @@ -45,6 +46,7 @@ #include "Option.h" #include "DownloadContext.h" #include "download_helper.h" +#include "fmt.h" namespace aria2 { @@ -65,10 +67,8 @@ void MetalinkPostDownloadHandler::getNextRequestGroups (std::vector<SharedHandle<RequestGroup> >& groups, RequestGroup* requestGroup) { - if(getLogger()->debug()) { - getLogger()->debug("Generating RequestGroups for Metalink file %s", - requestGroup->getFirstFilePath().c_str()); - } + A2_LOG_DEBUG(fmt("Generating RequestGroups for Metalink file %s", + requestGroup->getFirstFilePath().c_str())); SharedHandle<DiskAdaptor> diskAdaptor = requestGroup->getPieceStorage()->getDiskAdaptor(); try { diff --git a/src/MultiDiskAdaptor.cc b/src/MultiDiskAdaptor.cc index 3e574613..aea21c43 100644 --- a/src/MultiDiskAdaptor.cc +++ b/src/MultiDiskAdaptor.cc @@ -47,14 +47,19 @@ #include "DlAbortEx.h" #include "File.h" #include "StringFormat.h" +#include "fmt.h" #include "Logger.h" +#include "LogFactory.h" #include "SimpleRandomizer.h" namespace aria2 { -DiskWriterEntry::DiskWriterEntry(const SharedHandle<FileEntry>& fileEntry): - fileEntry_(fileEntry), open_(false), directIO_(false), - needsFileAllocation_(false) {} +DiskWriterEntry::DiskWriterEntry(const SharedHandle<FileEntry>& fileEntry) + : fileEntry_(fileEntry), + open_(false), + directIO_(false), + needsFileAllocation_(false) +{} const std::string& DiskWriterEntry::getFilePath() const { @@ -138,11 +143,12 @@ void DiskWriterEntry::disableDirectIO() directIO_ = false; } -MultiDiskAdaptor::MultiDiskAdaptor(): - pieceLength_(0), - maxOpenFiles_(DEFAULT_MAX_OPEN_FILES), - directIOAllowed_(false), - readOnly_(false) {} +MultiDiskAdaptor::MultiDiskAdaptor() + : pieceLength_(0), + maxOpenFiles_(DEFAULT_MAX_OPEN_FILES), + directIOAllowed_(false), + readOnly_(false) +{} MultiDiskAdaptor::~MultiDiskAdaptor() {} @@ -207,31 +213,25 @@ void MultiDiskAdaptor::resetDiskWriterEntries() off_t lastPieceStartOffset = (fileEntry->getOffset()+fileEntry->getLength()-1)/ pieceLength_*pieceLength_; - if(getLogger()->debug()) { - getLogger()->debug("Checking adjacent backward file to %s" - " whose lastPieceStartOffset+pieceLength_=%lld", - fileEntry->getPath().c_str(), - static_cast<long long int> - (lastPieceStartOffset+pieceLength_)); - } + A2_LOG_DEBUG(fmt("Checking adjacent backward file to %s" + " whose lastPieceStartOffset+pieceLength_=%lld", + fileEntry->getPath().c_str(), + static_cast<long long int> + (lastPieceStartOffset+pieceLength_))); ++itr; // adjacent backward files are not needed to be allocated. They // just requre DiskWriter for(; itr != eoi && (!(*itr)->getFileEntry()->isRequested() || (*itr)->getFileEntry()->getLength() == 0); ++itr) { - if(getLogger()->debug()) { - getLogger()->debug("file=%s, offset=%lld", - (*itr)->getFileEntry()->getPath().c_str(), - static_cast<long long int> - ((*itr)->getFileEntry()->getOffset())); - } + A2_LOG_DEBUG(fmt("file=%s, offset=%lld", + (*itr)->getFileEntry()->getPath().c_str(), + static_cast<long long int> + ((*itr)->getFileEntry()->getOffset()))); if((*itr)->getFileEntry()->getOffset() < static_cast<off_t>(lastPieceStartOffset+pieceLength_)) { - if(getLogger()->debug()) { - getLogger()->debug("%s needs diskwriter", - (*itr)->getFileEntry()->getPath().c_str()); - } + A2_LOG_DEBUG(fmt("%s needs diskwriter", + (*itr)->getFileEntry()->getPath().c_str())); dwreq[(*itr)->getFileEntry()->getPath()] = true; } else { break; @@ -251,10 +251,8 @@ void MultiDiskAdaptor::resetDiskWriterEntries() if((*i)->needsFileAllocation() || dwreq.find((*i)->getFileEntry()->getPath()) != dwreq.end() || (*i)->fileExists()) { - if(getLogger()->debug()) { - getLogger()->debug("Creating DiskWriter for filename=%s", - (*i)->getFilePath().c_str()); - } + A2_LOG_DEBUG(fmt("Creating DiskWriter for filename=%s", + (*i)->getFilePath().c_str())); (*i)->setDiskWriter(dwFactory.newDiskWriter((*i)->getFilePath())); if(directIOAllowed_) { (*i)->getDiskWriter()->allowDirectIO(); @@ -279,8 +277,8 @@ void MultiDiskAdaptor::openIfNot (const SharedHandle<DiskWriterEntry>& entry, void (DiskWriterEntry::*open)()) { if(!entry->isOpen()) { - // getLogger()->debug("DiskWriterEntry: Cache MISS. offset=%s", - // util::itos(entry->getFileEntry()->getOffset()).c_str()); + // A2_LOG_DEBUG(fmt("DiskWriterEntry: Cache MISS. offset=%s", + // util::itos(entry->getFileEntry()->getOffset()).c_str())); size_t numOpened = openedDiskWriterEntries_.size(); (entry.get()->*open)(); @@ -298,8 +296,8 @@ void MultiDiskAdaptor::openIfNot openedDiskWriterEntries_.push_back(entry); } } else { - // getLogger()->debug("DiskWriterEntry: Cache HIT. offset=%s", - // util::itos(entry->getFileEntry()->getOffset()).c_str()); + // A2_LOG_DEBUG(fmt("DiskWriterEntry: Cache HIT. offset=%s", + // util::itos(entry->getFileEntry()->getOffset()).c_str())); } } diff --git a/src/MultiUrlRequestInfo.cc b/src/MultiUrlRequestInfo.cc index edbfab88..e7e01fdb 100644 --- a/src/MultiUrlRequestInfo.cc +++ b/src/MultiUrlRequestInfo.cc @@ -56,6 +56,7 @@ #include "AuthConfigFactory.h" #include "SessionSerializer.h" #include "TimeA2.h" +#include "fmt.h" #ifdef ENABLE_SSL # include "SocketCore.h" # include "TLSContext.h" @@ -94,12 +95,10 @@ MultiUrlRequestInfo::MultiUrlRequestInfo const SharedHandle<Option>& op, const SharedHandle<StatCalc>& statCalc, std::ostream& summaryOut) - : - requestGroups_(requestGroups), - option_(op), - statCalc_(statCalc), - summaryOut_(summaryOut), - logger_(LogFactory::getInstance()) + : requestGroups_(requestGroups), + option_(op), + statCalc_(statCalc), + summaryOut_(summaryOut) {} MultiUrlRequestInfo::~MultiUrlRequestInfo() {} @@ -124,10 +123,11 @@ downloadresultcode::RESULT MultiUrlRequestInfo::execute() File cookieFile(option_->get(PREF_LOAD_COOKIES)); if(cookieFile.isFile()) { e->getCookieStorage()->load(cookieFile.getPath(), Time().getTime()); - logger_->info("Loaded cookies from '%s'.", - cookieFile.getPath().c_str()); + A2_LOG_INFO(fmt("Loaded cookies from '%s'.", + cookieFile.getPath().c_str())); } else { - logger_->error(MSG_LOADING_COOKIE_FAILED, cookieFile.getPath().c_str()); + A2_LOG_ERROR(fmt(MSG_LOADING_COOKIE_FAILED, + cookieFile.getPath().c_str())); } } @@ -136,8 +136,8 @@ downloadresultcode::RESULT MultiUrlRequestInfo::execute() if(!option_->getAsBool(PREF_NO_NETRC) && netrccf.isFile()) { mode_t mode = netrccf.mode(); if(mode&(S_IRWXG|S_IRWXO)) { - logger_->notice(MSG_INCORRECT_NETRC_PERMISSION, - option_->get(PREF_NETRC_PATH).c_str()); + A2_LOG_NOTICE(fmt(MSG_INCORRECT_NETRC_PERMISSION, + option_->get(PREF_NETRC_PATH).c_str())); } else { SharedHandle<Netrc> netrc(new Netrc()); netrc->parse(option_->get(PREF_NETRC_PATH)); @@ -155,10 +155,10 @@ downloadresultcode::RESULT MultiUrlRequestInfo::execute() } if(!option_->blank(PREF_CA_CERTIFICATE)) { if(!tlsContext->addTrustedCACertFile(option_->get(PREF_CA_CERTIFICATE))) { - logger_->info(MSG_WARN_NO_CA_CERT); + A2_LOG_INFO(MSG_WARN_NO_CA_CERT); } } else if(option_->getAsBool(PREF_CHECK_CERTIFICATE)) { - logger_->info(MSG_WARN_NO_CA_CERT); + A2_LOG_INFO(MSG_WARN_NO_CA_CERT); } if(option_->getAsBool(PREF_CHECK_CERTIFICATE)) { tlsContext->enablePeerVerification(); @@ -166,8 +166,8 @@ downloadresultcode::RESULT MultiUrlRequestInfo::execute() SocketCore::setTLSContext(tlsContext); #endif if(!Timer::monotonicClock()) { - logger_->warn("Don't change system time while aria2c is running." - " Doing this may make aria2c hang for long time."); + A2_LOG_WARN("Don't change system time while aria2c is running." + " Doing this may make aria2c hang for long time."); } std::string serverStatIf = option_->get(PREF_SERVER_STAT_IF); @@ -212,18 +212,18 @@ downloadresultcode::RESULT MultiUrlRequestInfo::execute() if(!option_->blank(PREF_SAVE_SESSION)) { const std::string& filename = option_->get(PREF_SAVE_SESSION); if(sessionSerializer.save(filename)) { - logger_->notice("Serialized session to '%s' successfully.", - filename.c_str()); + A2_LOG_NOTICE(fmt("Serialized session to '%s' successfully.", + filename.c_str())); } else { - logger_->notice("Failed to serialize session to '%s'.", - filename.c_str()); + A2_LOG_NOTICE(fmt("Failed to serialize session to '%s'.", + filename.c_str())); } } } catch(RecoverableException& e) { if(returnValue == downloadresultcode::FINISHED) { returnValue = downloadresultcode::UNKNOWN_ERROR; } - logger_->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } #ifdef SIGHUP util::setGlobalSignalHandler(SIGHUP, SIG_DFL, 0); diff --git a/src/MultiUrlRequestInfo.h b/src/MultiUrlRequestInfo.h index d3c4bb58..1ca4c4be 100644 --- a/src/MultiUrlRequestInfo.h +++ b/src/MultiUrlRequestInfo.h @@ -47,7 +47,6 @@ namespace aria2 { class RequestGroup; class Option; -class Logger; class StatCalc; class MultiUrlRequestInfo { @@ -60,10 +59,7 @@ private: std::ostream& summaryOut_; - Logger* logger_; - void printMessageForContinue(); - public: MultiUrlRequestInfo (const std::vector<SharedHandle<RequestGroup> >& requestGroups, diff --git a/src/PeerAbstractCommand.cc b/src/PeerAbstractCommand.cc index d77afb66..6b068c1c 100644 --- a/src/PeerAbstractCommand.cc +++ b/src/PeerAbstractCommand.cc @@ -39,29 +39,32 @@ #include "DlAbortEx.h" #include "Socket.h" #include "Logger.h" +#include "LogFactory.h" #include "message.h" #include "prefs.h" #include "DownloadFailureException.h" #include "StringFormat.h" +#include "fmt.h" #include "wallclock.h" #include "util.h" namespace aria2 { -PeerAbstractCommand::PeerAbstractCommand(cuid_t cuid, - const SharedHandle<Peer>& peer, - DownloadEngine* e, - const SocketHandle& s): - Command(cuid), - checkPoint_(global::wallclock), - // TODO referring global option - timeout_(e->getOption()->getAsInt(PREF_BT_TIMEOUT)), - e_(e), - socket_(s), - peer_(peer), - checkSocketIsReadable_(false), - checkSocketIsWritable_(false), - noCheck_(false) +PeerAbstractCommand::PeerAbstractCommand +(cuid_t cuid, + const SharedHandle<Peer>& peer, + DownloadEngine* e, + const SocketHandle& s) + : Command(cuid), + checkPoint_(global::wallclock), + // TODO referring global option + timeout_(e->getOption()->getAsInt(PREF_BT_TIMEOUT)), + e_(e), + socket_(s), + peer_(peer), + checkSocketIsReadable_(false), + checkSocketIsWritable_(false), + noCheck_(false) { if(socket_ && socket_->isOpen()) { setReadCheckSocket(socket_); @@ -76,14 +79,12 @@ PeerAbstractCommand::~PeerAbstractCommand() bool PeerAbstractCommand::execute() { - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s -" - " socket: read:%d, write:%d, hup:%d, err:%d, noCheck:%d", - util::itos(getCuid()).c_str(), - readEventEnabled(), writeEventEnabled(), - hupEventEnabled(), errorEventEnabled(), - noCheck_); - } + A2_LOG_DEBUG(fmt("CUID#%s -" + " socket: read:%d, write:%d, hup:%d, err:%d, noCheck:%d", + util::itos(getCuid()).c_str(), + readEventEnabled(), writeEventEnabled(), + hupEventEnabled(), errorEventEnabled(), + noCheck_)); if(exitBeforeExecute()) { onAbort(); return true; @@ -104,19 +105,18 @@ bool PeerAbstractCommand::execute() } return executeInternal(); } catch(DownloadFailureException& err) { - getLogger()->error(EX_DOWNLOAD_ABORTED, err); + A2_LOG_ERROR_EX(EX_DOWNLOAD_ABORTED, err); onAbort(); onFailure(); return true; } catch(RecoverableException& err) { - if(getLogger()->debug()) { - getLogger()->debug(MSG_TORRENT_DOWNLOAD_ABORTED, err, - util::itos(getCuid()).c_str()); - getLogger()->debug(MSG_PEER_BANNED, - util::itos(getCuid()).c_str(), - peer_->getIPAddress().c_str(), - peer_->getPort()); - } + A2_LOG_DEBUG_EX(fmt(MSG_TORRENT_DOWNLOAD_ABORTED, + util::itos(getCuid()).c_str()), + err); + A2_LOG_DEBUG(fmt(MSG_PEER_BANNED, + util::itos(getCuid()).c_str(), + peer_->getIPAddress().c_str(), + peer_->getPort())); onAbort(); return prepareForNextPeer(0); } diff --git a/src/PeerConnection.cc b/src/PeerConnection.cc index 23d12093..cf31cd23 100644 --- a/src/PeerConnection.cc +++ b/src/PeerConnection.cc @@ -48,6 +48,7 @@ #include "ARC4Encryptor.h" #include "ARC4Decryptor.h" #include "StringFormat.h" +#include "fmt.h" #include "util.h" #include "Peer.h" @@ -55,18 +56,16 @@ namespace aria2 { PeerConnection::PeerConnection (cuid_t cuid, const SharedHandle<Peer>& peer, const SocketHandle& socket) - - :cuid_(cuid), - peer_(peer), - socket_(socket), - logger_(LogFactory::getInstance()), - resbuf_(new unsigned char[MAX_PAYLOAD_LEN]), - resbufLength_(0), - currentPayloadLength_(0), - lenbufLength_(0), - socketBuffer_(socket), - encryptionEnabled_(false), - prevPeek_(false) + : cuid_(cuid), + peer_(peer), + socket_(socket), + resbuf_(new unsigned char[MAX_PAYLOAD_LEN]), + resbufLength_(0), + currentPayloadLength_(0), + lenbufLength_(0), + socketBuffer_(socket), + encryptionEnabled_(false), + prevPeek_(false) {} PeerConnection::~PeerConnection() @@ -124,12 +123,10 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) { return false; } // we got EOF - if(logger_->debug()) { - logger_->debug("CUID#%s - In PeerConnection::receiveMessage()," + A2_LOG_DEBUG(fmt("CUID#%s - In PeerConnection::receiveMessage()," " remain=%lu", util::itos(cuid_).c_str(), - static_cast<unsigned long>(temp)); - } + static_cast<unsigned long>(temp))); peer_->setDisconnectedGracefully(true); throw DL_ABORT_EX(EX_EOF_FROM_PEER); } @@ -159,13 +156,11 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) { return false; } // we got EOF - if(logger_->debug()) { - logger_->debug("CUID#%s - In PeerConnection::receiveMessage()," + A2_LOG_DEBUG(fmt("CUID#%s - In PeerConnection::receiveMessage()," " payloadlen=%lu, remaining=%lu", util::itos(cuid_).c_str(), static_cast<unsigned long>(currentPayloadLength_), - static_cast<unsigned long>(temp)); - } + static_cast<unsigned long>(temp))); peer_->setDisconnectedGracefully(true); throw DL_ABORT_EX(EX_EOF_FROM_PEER); } @@ -212,11 +207,10 @@ bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength, return false; } // we got EOF - if(logger_->debug()) { - logger_->debug - ("CUID#%s - In PeerConnection::receiveHandshake(), remain=%lu", - util::itos(cuid_).c_str(), static_cast<unsigned long>(temp)); - } + A2_LOG_DEBUG + (fmt("CUID#%s - In PeerConnection::receiveHandshake(), remain=%lu", + util::itos(cuid_).c_str(), + static_cast<unsigned long>(temp))); peer_->setDisconnectedGracefully(true); throw DL_ABORT_EX(EX_EOF_FROM_PEER); } @@ -273,9 +267,7 @@ bool PeerConnection::sendBufferIsEmpty() const ssize_t PeerConnection::sendPendingData() { ssize_t writtenLength = socketBuffer_.send(); - if(logger_->debug()) { - logger_->debug("sent %ld byte(s).", static_cast<long int>(writtenLength)); - } + A2_LOG_DEBUG(fmt("sent %ld byte(s).", static_cast<long int>(writtenLength))); return writtenLength; } diff --git a/src/PeerConnection.h b/src/PeerConnection.h index fd2acd7a..0557204d 100644 --- a/src/PeerConnection.h +++ b/src/PeerConnection.h @@ -45,7 +45,6 @@ namespace aria2 { -class Logger; class Peer; class SocketCore; class ARC4Encryptor; @@ -60,7 +59,6 @@ private: cuid_t cuid_; SharedHandle<Peer> peer_; SharedHandle<SocketCore> socket_; - Logger* logger_; unsigned char* resbuf_; size_t resbufLength_; diff --git a/src/PeerInitiateConnectionCommand.cc b/src/PeerInitiateConnectionCommand.cc index 95e62869..3c258d57 100644 --- a/src/PeerInitiateConnectionCommand.cc +++ b/src/PeerInitiateConnectionCommand.cc @@ -41,6 +41,7 @@ #include "prefs.h" #include "Socket.h" #include "Logger.h" +#include "LogFactory.h" #include "Peer.h" #include "BtRuntime.h" #include "PeerStorage.h" @@ -48,6 +49,7 @@ #include "PeerConnection.h" #include "RequestGroup.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -58,11 +60,10 @@ PeerInitiateConnectionCommand::PeerInitiateConnectionCommand DownloadEngine* e, const SharedHandle<BtRuntime>& btRuntime, bool mseHandshakeEnabled) - : - PeerAbstractCommand(cuid, peer, e), - requestGroup_(requestGroup), - btRuntime_(btRuntime), - mseHandshakeEnabled_(mseHandshakeEnabled) + : PeerAbstractCommand(cuid, peer, e), + requestGroup_(requestGroup), + btRuntime_(btRuntime), + mseHandshakeEnabled_(mseHandshakeEnabled) { btRuntime_->increaseConnections(); requestGroup_->increaseNumCommand(); @@ -75,12 +76,10 @@ PeerInitiateConnectionCommand::~PeerInitiateConnectionCommand() } bool PeerInitiateConnectionCommand::executeInternal() { - if(getLogger()->info()) { - getLogger()->info(MSG_CONNECTING_TO_SERVER, - util::itos(getCuid()).c_str(), - getPeer()->getIPAddress().c_str(), - getPeer()->getPort()); - } + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, + util::itos(getCuid()).c_str(), + getPeer()->getIPAddress().c_str(), + getPeer()->getPort())); createSocket(); getSocket()->establishConnection(getPeer()->getIPAddress(), getPeer()->getPort()); diff --git a/src/PeerListenCommand.cc b/src/PeerListenCommand.cc index 25188e07..2ce07b38 100644 --- a/src/PeerListenCommand.cc +++ b/src/PeerListenCommand.cc @@ -44,9 +44,11 @@ #include "message.h" #include "ReceiverMSEHandshakeCommand.h" #include "Logger.h" +#include "LogFactory.h" #include "Socket.h" #include "SimpleRandomizer.h" #include "util.h" +#include "fmt.h" namespace aria2 { @@ -57,11 +59,13 @@ PeerListenCommand* PeerListenCommand::instance_ = 0; PeerListenCommand* PeerListenCommand::instance6_ = 0; PeerListenCommand::PeerListenCommand -(cuid_t cuid, DownloadEngine* e, int family): - Command(cuid), - e_(e), - family_(family), - lowestSpeedLimit_(20*1024) +(cuid_t cuid, + DownloadEngine* e, + int family) + : Command(cuid), + e_(e), + family_(family), + lowestSpeedLimit_(20*1024) { ++numInstance_; } @@ -89,12 +93,13 @@ bool PeerListenCommand::bindPort(uint16_t& port, IntSequence& seq) socket_->bind(A2STR::NIL, port, family_); socket_->beginListen(); socket_->setNonBlockingMode(); - getLogger()->notice("IPv%d BitTorrent: listening to port %d", - family_ == AF_INET?4:6, port); + A2_LOG_NOTICE(fmt("IPv%d BitTorrent: listening to port %d", + family_ == AF_INET?4:6, port)); return true; } catch(RecoverableException& ex) { - getLogger()->error(MSG_BIND_FAILURE, ex, - util::itos(getCuid()).c_str(), port); + A2_LOG_ERROR_EX(fmt(MSG_BIND_FAILURE, + util::itos(getCuid()).c_str(), port), + ex); socket_->closeConnection(); } } @@ -130,16 +135,16 @@ bool PeerListenCommand::execute() { Command* command = new ReceiverMSEHandshakeCommand(cuid, peer, e_, peerSocket); e_->addCommand(command); - if(getLogger()->debug()) { - getLogger()->debug("Accepted the connection from %s:%u.", - peer->getIPAddress().c_str(), - peer->getPort()); - getLogger()->debug("Added CUID#%s to receive BitTorrent/MSE handshake.", - util::itos(cuid).c_str()); - } + A2_LOG_DEBUG(fmt("Accepted the connection from %s:%u.", + peer->getIPAddress().c_str(), + peer->getPort())); + A2_LOG_DEBUG(fmt("Added CUID#%s to receive BitTorrent/MSE handshake.", + util::itos(cuid).c_str())); } catch(RecoverableException& ex) { - getLogger()->debug(MSG_ACCEPT_FAILURE, ex, util::itos(getCuid()).c_str()); - } + A2_LOG_DEBUG_EX(fmt(MSG_ACCEPT_FAILURE, + util::itos(getCuid()).c_str()), + ex); + } } e_->addCommand(this); return false; diff --git a/src/PeerReceiveHandshakeCommand.cc b/src/PeerReceiveHandshakeCommand.cc index 867399ab..d2de0ac8 100644 --- a/src/PeerReceiveHandshakeCommand.cc +++ b/src/PeerReceiveHandshakeCommand.cc @@ -49,10 +49,12 @@ #include "message.h" #include "Socket.h" #include "Logger.h" +#include "LogFactory.h" #include "prefs.h" #include "Option.h" #include "RequestGroupMan.h" #include "StringFormat.h" +#include "fmt.h" #include "RequestGroup.h" namespace aria2 { @@ -63,9 +65,8 @@ PeerReceiveHandshakeCommand::PeerReceiveHandshakeCommand DownloadEngine* e, const SocketHandle& s, const SharedHandle<PeerConnection>& peerConnection) - : - PeerAbstractCommand(cuid, peer, e, s), - peerConnection_(peerConnection) + : PeerAbstractCommand(cuid, peer, e, s), + peerConnection_(peerConnection) { if(!peerConnection_) { peerConnection_.reset(new PeerConnection(cuid, getPeer(), getSocket())); @@ -110,8 +111,8 @@ bool PeerReceiveHandshakeCommand::executeInternal() util::toHex(infoHash).c_str()).str()); } if(btRuntime->isHalt()) { - getLogger()->debug("Info hash found but the download is over." - " Dropping connection."); + A2_LOG_DEBUG("Info hash found but the download is over." + " Dropping connection."); return true; } TransferStat tstat = @@ -143,11 +144,9 @@ bool PeerReceiveHandshakeCommand::executeInternal() PeerInteractionCommand::RECEIVER_WAIT_HANDSHAKE, peerConnection_); getDownloadEngine()->addCommand(command); - if(getLogger()->debug()) { - getLogger()->debug(MSG_INCOMING_PEER_CONNECTION, - util::itos(getCuid()).c_str(), - util::itos(getPeer()->usedBy()).c_str()); - } + A2_LOG_DEBUG(fmt(MSG_INCOMING_PEER_CONNECTION, + util::itos(getCuid()).c_str(), + util::itos(getPeer()->usedBy()).c_str())); } } return true; diff --git a/src/PollEventPoll.cc b/src/PollEventPoll.cc index 1af0771d..e5933e24 100644 --- a/src/PollEventPoll.cc +++ b/src/PollEventPoll.cc @@ -42,11 +42,13 @@ #include "LogFactory.h" #include "Logger.h" #include "a2functional.h" +#include "fmt.h" namespace aria2 { -PollEventPoll::KSocketEntry::KSocketEntry(sock_t s): - SocketEntry<KCommandEvent, KADNSEvent>(s) {} +PollEventPoll::KSocketEntry::KSocketEntry(sock_t s) + : SocketEntry<KCommandEvent, KADNSEvent>(s) +{} int accumulateEvent(int events, const PollEventPoll::KEvent& event) { @@ -73,8 +75,9 @@ struct pollfd PollEventPoll::KSocketEntry::getEvents() return pollEvent; } -PollEventPoll::PollEventPoll(): - pollfdCapacity_(1024), pollfdNum_(0), logger_(LogFactory::getInstance()) +PollEventPoll::PollEventPoll() + : pollfdCapacity_(1024), + pollfdNum_(0) { pollfds_ = new struct pollfd[pollfdCapacity_]; } @@ -103,10 +106,8 @@ void PollEventPoll::poll(const struct timeval& tv) if(itr != socketEntries_.end() && *(*itr) == *se) { (*itr)->processEvents(first->revents); } else { - if(logger_->debug()) { - logger_->debug("Socket %d is not found in SocketEntries.", - first->fd); - } + A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", + first->fd)); } } } @@ -221,9 +222,7 @@ bool PollEventPoll::deleteEvents } return true; } else { - if(logger_->debug()) { - logger_->debug("Socket %d is not found in SocketEntries.", socket); - } + A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket)); return false; } } diff --git a/src/PollEventPoll.h b/src/PollEventPoll.h index eddac2c9..b07a5308 100644 --- a/src/PollEventPoll.h +++ b/src/PollEventPoll.h @@ -48,8 +48,6 @@ namespace aria2 { -class Logger; - class PollEventPoll : public EventPoll { private: class KSocketEntry; @@ -84,8 +82,6 @@ private: struct pollfd* pollfds_; - Logger* logger_; - bool addEvents(sock_t socket, const KEvent& event); bool deleteEvents(sock_t socket, const KEvent& event); diff --git a/src/PortEventPoll.cc b/src/PortEventPoll.cc index 363c619f..10766a67 100644 --- a/src/PortEventPoll.cc +++ b/src/PortEventPoll.cc @@ -43,11 +43,13 @@ #include "LogFactory.h" #include "Logger.h" #include "util.h" +#include "fmt.h" namespace aria2 { -PortEventPoll::KSocketEntry::KSocketEntry(sock_t s): - SocketEntry<KCommandEvent, KADNSEvent>(s) {} +PortEventPoll::KSocketEntry::KSocketEntry(sock_t s) + : SocketEntry<KCommandEvent, KADNSEvent>(s) +{} int accumulateEvent(int events, const PortEventPoll::KEvent& event) { @@ -74,10 +76,9 @@ PortEventPoll::A2PortEvent PortEventPoll::KSocketEntry::getEvents() return portEvent; } -PortEventPoll::PortEventPoll(): - portEventsSize_(PORT_EVENTS_SIZE), - portEvents_(new port_event_t[portEventsSize_]), - logger_(LogFactory::getInstance()) +PortEventPoll::PortEventPoll() + : portEventsSize_(PORT_EVENTS_SIZE), + portEvents_(new port_event_t[portEventsSize_]) { port_ = port_create(); } @@ -89,8 +90,9 @@ PortEventPoll::~PortEventPoll() while((r = close(port_)) == -1 && errno == EINTR); int errNum = errno; if(r == -1) { - logger_->error("Error occurred while closing port %d: %s", - port_, util::safeStrerror(errNum).c_str()); + A2_LOG_ERROR(fmt("Error occurred while closing port %d: %s", + port_, + util::safeStrerror(errNum).c_str())); } } delete [] portEvents_; @@ -114,9 +116,7 @@ void PortEventPoll::poll(const struct timeval& tv) if(res == 0 || (res == -1 && (errno == ETIME || errno == EINTR) && portEvents_[0].portev_user != (void*)-1)) { - if(logger_->debug()) { - logger_->debug("nget=%u", nget); - } + A2_LOG_DEBUG(fmt("nget=%u", nget)); for(uint_t i = 0; i < nget; ++i) { const port_event_t& pev = portEvents_[i]; KSocketEntry* p = reinterpret_cast<KSocketEntry*>(pev.portev_user); @@ -125,8 +125,10 @@ void PortEventPoll::poll(const struct timeval& tv) p->getEvents().events, p); int errNum = errno; if(r == -1) { - logger_->error("port_associate failed for file descriptor %d: cause %s", - pev.portev_object, util::safeStrerror(errNum).c_str()); + A2_LOG_ERROR(fmt("port_associate failed for file descriptor %d:" + " cause %s", + pev.portev_object, + util::safeStrerror(errNum).c_str())); } } } @@ -197,10 +199,8 @@ bool PortEventPoll::addEvents(sock_t socket, errNum = r; } if(r == -1) { - if(logger_->debug()) { - logger_->debug("Failed to add socket event %d:%s", - socket, util::safeStrerror(errNum).c_str()); - } + A2_LOG_DEBUG(fmt("Failed to add socket event %d:%s", + socket, util::safeStrerror(errNum).c_str())); return false; } else { return true; @@ -244,18 +244,14 @@ bool PortEventPoll::deleteEvents(sock_t socket, errNum = errno; } if(r == -1) { - if(logger_->debug()) { - logger_->debug("Failed to delete socket event:%s", - util::safeStrerror(errNum).c_str()); - } + A2_LOG_DEBUG(fmt("Failed to delete socket event:%s", + util::safeStrerror(errNum).c_str())); return false; } else { return true; } } else { - if(logger_->debug()) { - logger_->debug("Socket %d is not found in SocketEntries.", socket); - } + A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket)); return false; } } diff --git a/src/PortEventPoll.h b/src/PortEventPoll.h index 9abc7d81..937e629e 100644 --- a/src/PortEventPoll.h +++ b/src/PortEventPoll.h @@ -50,8 +50,6 @@ namespace aria2 { -class Logger; - class PortEventPoll : public EventPoll { private: class KSocketEntry; @@ -91,8 +89,6 @@ private: static const size_t PORT_EVENTS_SIZE = 1024; - Logger* logger_; - bool addEvents(sock_t socket, const KEvent& event); bool deleteEvents(sock_t socket, const KEvent& event); diff --git a/src/RequestGroup.cc b/src/RequestGroup.cc index 22472325..88c2ea79 100644 --- a/src/RequestGroup.cc +++ b/src/RequestGroup.cc @@ -69,6 +69,7 @@ #include "Request.h" #include "FileAllocationIterator.h" #include "StringFormat.h" +#include "fmt.h" #include "A2STR.h" #include "URISelector.h" #include "InOrderURISelector.h" @@ -121,35 +122,34 @@ namespace aria2 { gid_t RequestGroup::gidCounter_ = 0; -RequestGroup::RequestGroup(const SharedHandle<Option>& option): - gid_(newGID()), - option_(new Option(*option.get())), - numConcurrentCommand_(option->getAsInt(PREF_SPLIT)), - numStreamConnection_(0), - numStreamCommand_(0), - numCommand_(0), - saveControlFile_(true), - progressInfoFile_(new NullProgressInfoFile()), - preLocalFileCheckEnabled_(true), - haltRequested_(false), - forceHaltRequested_(false), - haltReason_(RequestGroup::NONE), - pauseRequested_(false), - uriSelector_(new InOrderURISelector()), - lastModifiedTime_(Time::null()), - fileNotFoundCount_(0), - timeout_(option->getAsInt(PREF_TIMEOUT)), +RequestGroup::RequestGroup(const SharedHandle<Option>& option) + : gid_(newGID()), + option_(new Option(*option.get())), + numConcurrentCommand_(option->getAsInt(PREF_SPLIT)), + numStreamConnection_(0), + numStreamCommand_(0), + numCommand_(0), + saveControlFile_(true), + progressInfoFile_(new NullProgressInfoFile()), + preLocalFileCheckEnabled_(true), + haltRequested_(false), + forceHaltRequested_(false), + haltReason_(RequestGroup::NONE), + pauseRequested_(false), + uriSelector_(new InOrderURISelector()), + lastModifiedTime_(Time::null()), + fileNotFoundCount_(0), + timeout_(option->getAsInt(PREF_TIMEOUT)), #ifdef ENABLE_BITTORRENT - btRuntime_(0), - peerStorage_(0), + btRuntime_(0), + peerStorage_(0), #endif // ENABLE_BITTORRENT - inMemoryDownload_(false), - maxDownloadSpeedLimit_(option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT)), - maxUploadSpeedLimit_(option->getAsInt(PREF_MAX_UPLOAD_LIMIT)), - belongsToGID_(0), - requestGroupMan_(0), - resumeFailureCount_(0), - logger_(LogFactory::getInstance()) + inMemoryDownload_(false), + maxDownloadSpeedLimit_(option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT)), + maxUploadSpeedLimit_(option->getAsInt(PREF_MAX_UPLOAD_LIMIT)), + belongsToGID_(0), + requestGroupMan_(0), + resumeFailureCount_(0) { fileAllocationEnabled_ = option_->get(PREF_FILE_ALLOCATION) != V_NONE; // Add types to be sent as a Accept header value here. @@ -235,9 +235,7 @@ SharedHandle<CheckIntegrityEntry> RequestGroup::createCheckIntegrityEntry() if(downloadFinished()) { #ifdef ENABLE_MESSAGE_DIGEST if(downloadContext_->isChecksumVerificationNeeded()) { - if(logger_->info()) { - logger_->info(MSG_HASH_CHECK_NOT_DONE); - } + A2_LOG_INFO(MSG_HASH_CHECK_NOT_DONE); ChecksumCheckIntegrityEntry* tempEntry = new ChecksumCheckIntegrityEntry(this); tempEntry->setRedownload(true); @@ -246,9 +244,9 @@ SharedHandle<CheckIntegrityEntry> RequestGroup::createCheckIntegrityEntry() #endif // ENABLE_MESSAGE_DIGEST { downloadContext_->setChecksumVerified(true); - logger_->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, - util::itos(gid_).c_str(), - downloadContext_->getBasePath().c_str()); + A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED, + util::itos(gid_).c_str(), + downloadContext_->getBasePath().c_str())); } } else { checkEntry.reset(new StreamCheckIntegrityEntry(this)); @@ -267,9 +265,9 @@ SharedHandle<CheckIntegrityEntry> RequestGroup::createCheckIntegrityEntry() #endif // ENABLE_MESSAGE_DIGEST { downloadContext_->setChecksumVerified(true); - logger_->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, - util::itos(gid_).c_str(), - downloadContext_->getBasePath().c_str()); + A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED, + util::itos(gid_).c_str(), + downloadContext_->getBasePath().c_str())); } } else { loadAndOpenFile(infoFile); @@ -378,8 +376,8 @@ void RequestGroup::createInitialCommand e->addCommand(dhtCommands); } } else { - logger_->notice("For BitTorrent Magnet URI, enabling DHT is strongly" - " recommended. See --enable-dht option."); + A2_LOG_NOTICE("For BitTorrent Magnet URI, enabling DHT is strongly" + " recommended. See --enable-dht option."); } SharedHandle<CheckIntegrityEntry> entry @@ -398,12 +396,11 @@ void RequestGroup::createInitialCommand } else { // Open file in writable mode to allow the program // truncate the file to downloadContext_->getTotalLength() - if(logger_->debug()) { - logger_->debug("File size not match. File is opened in writable" - " mode. Expected:%s Actual:%s", - util::uitos(downloadContext_->getTotalLength()).c_str(), - util::uitos(actualFileSize).c_str()); - } + A2_LOG_DEBUG + (fmt("File size not match. File is opened in writable" + " mode. Expected:%s Actual:%s", + util::uitos(downloadContext_->getTotalLength()).c_str(), + util::uitos(actualFileSize).c_str())); } } // Call Load, Save and file allocation command here @@ -600,9 +597,7 @@ void RequestGroup::initPieceStorage() // Use LongestSequencePieceSelector when HTTP/FTP/BitTorrent // integrated downloads. Currently multi-file integrated // download is not supported. - if(logger_->debug()) { - logger_->debug("Using LongestSequencePieceSelector"); - } + A2_LOG_DEBUG("Using LongestSequencePieceSelector"); SharedHandle<PieceSelector> longestPieceSelector (new LongestSequencePieceSelector()); ps->setPieceSelector(longestPieceSelector); @@ -684,8 +679,9 @@ void RequestGroup::adjustFilename option_->getAsBool(PREF_REMOVE_CONTROL_FILE) && infoFile->exists()) { infoFile->removeFile(); - logger_->notice("Removed control file for %s because it is requested by" - " user.", infoFile->getFilename().c_str()); + A2_LOG_NOTICE(fmt("Removed control file for %s because it is requested by" + " user.", + infoFile->getFilename().c_str())); } if(infoFile->exists()) { // Use current filename @@ -717,9 +713,9 @@ void RequestGroup::removeDefunctControlFile if(progressInfoFile->exists() && !pieceStorage_->getDiskAdaptor()->fileExists()) { progressInfoFile->removeFile(); - logger_->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE, - progressInfoFile->getFilename().c_str(), - downloadContext_->getBasePath().c_str()); + A2_LOG_NOTICE(fmt(MSG_REMOVED_DEFUNCT_CONTROL_FILE, + progressInfoFile->getFilename().c_str(), + downloadContext_->getBasePath().c_str())); } } @@ -769,7 +765,7 @@ void RequestGroup::shouldCancelDownloadForSafety() if(outfile.exists()) { if(option_->getAsBool(PREF_AUTO_FILE_RENAMING)) { if(tryAutoFileRenaming()) { - logger_->notice(MSG_FILE_RENAMED, getFirstFilePath().c_str()); + A2_LOG_NOTICE(fmt(MSG_FILE_RENAMED, getFirstFilePath().c_str())); } else { throw DOWNLOAD_FAILURE_EXCEPTION (StringFormat("File renaming failed: %s", @@ -966,9 +962,7 @@ void RequestGroup::decreaseNumCommand() { --numCommand_; if(!numCommand_ && requestGroupMan_) { - if(logger_->debug()) { - logger_->debug("GID#%s - Request queue check", util::itos(gid_).c_str()); - } + A2_LOG_DEBUG(fmt("GID#%s - Request queue check", util::itos(gid_).c_str())); requestGroupMan_->requestQueueCheck(); } } @@ -1033,10 +1027,8 @@ void RequestGroup::releaseRuntimeResource(DownloadEngine* e) void RequestGroup::preDownloadProcessing() { - if(logger_->debug()) { - logger_->debug("Finding PreDownloadHandler for path %s.", - getFirstFilePath().c_str()); - } + A2_LOG_DEBUG(fmt("Finding PreDownloadHandler for path %s.", + getFirstFilePath().c_str())); try { for(std::vector<SharedHandle<PreDownloadHandler> >::const_iterator itr = preDownloadHandlers_.begin(), eoi = preDownloadHandlers_.end(); @@ -1047,22 +1039,18 @@ void RequestGroup::preDownloadProcessing() } } } catch(RecoverableException& ex) { - logger_->error(EX_EXCEPTION_CAUGHT, ex); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex); return; } - if(logger_->debug()) { - logger_->debug("No PreDownloadHandler found."); - } + A2_LOG_DEBUG("No PreDownloadHandler found."); return; } void RequestGroup::postDownloadProcessing (std::vector<SharedHandle<RequestGroup> >& groups) { - if(logger_->debug()) { - logger_->debug("Finding PostDownloadHandler for path %s.", - getFirstFilePath().c_str()); - } + A2_LOG_DEBUG(fmt("Finding PostDownloadHandler for path %s.", + getFirstFilePath().c_str())); try { for(std::vector<SharedHandle<PostDownloadHandler> >::const_iterator itr = postDownloadHandlers_.begin(), eoi = postDownloadHandlers_.end(); @@ -1073,11 +1061,9 @@ void RequestGroup::postDownloadProcessing } } } catch(RecoverableException& ex) { - logger_->error(EX_EXCEPTION_CAUGHT, ex); - } - if(logger_->debug()) { - logger_->debug("No PostDownloadHandler found."); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex); } + A2_LOG_DEBUG("No PostDownloadHandler found."); } void RequestGroup::initializePreDownloadHandler() @@ -1169,10 +1155,8 @@ bool RequestGroup::needsFileAllocation() const DownloadResultHandle RequestGroup::createDownloadResult() const { - if(logger_->debug()) { - logger_->debug("GID#%s - Creating DownloadResult.", - util::itos(gid_).c_str()); - } + A2_LOG_DEBUG(fmt("GID#%s - Creating DownloadResult.", + util::itos(gid_).c_str())); TransferStat st = calculateStat(); SharedHandle<DownloadResult> res(new DownloadResult()); res->gid = gid_; @@ -1207,8 +1191,8 @@ DownloadResultHandle RequestGroup::createDownloadResult() const void RequestGroup::reportDownloadFinished() { - logger_->notice(MSG_FILE_DOWNLOAD_COMPLETED, - downloadContext_->getBasePath().c_str()); + A2_LOG_NOTICE(fmt(MSG_FILE_DOWNLOAD_COMPLETED, + downloadContext_->getBasePath().c_str())); uriSelector_->resetCounters(); #ifdef ENABLE_BITTORRENT if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) { @@ -1218,10 +1202,10 @@ void RequestGroup::reportDownloadFinished() SharedHandle<TorrentAttribute> attrs = bittorrent::getTorrentAttrs(downloadContext_); if(!attrs->metadata.empty()) { - logger_->notice(MSG_SHARE_RATIO_REPORT, - shareRatio, - util::abbrevSize(stat.getAllTimeUploadLength()).c_str(), - util::abbrevSize(getCompletedLength()).c_str()); + A2_LOG_NOTICE(fmt(MSG_SHARE_RATIO_REPORT, + shareRatio, + util::abbrevSize(stat.getAllTimeUploadLength()).c_str(), + util::abbrevSize(getCompletedLength()).c_str())); } } #endif // ENABLE_BITTORRENT @@ -1248,12 +1232,12 @@ void RequestGroup::setURISelector(const SharedHandle<URISelector>& uriSelector) void RequestGroup::applyLastModifiedTimeToLocalFiles() { if(pieceStorage_ && lastModifiedTime_.good()) { - logger_->info("Applying Last-Modified time: %s", - lastModifiedTime_.toHTTPDate().c_str()); + A2_LOG_INFO(fmt("Applying Last-Modified time: %s", + lastModifiedTime_.toHTTPDate().c_str())); size_t n = pieceStorage_->getDiskAdaptor()->utime(Time(), lastModifiedTime_); - logger_->info("Last-Modified attrs of %lu files were updated.", - static_cast<unsigned long>(n)); + A2_LOG_INFO(fmt("Last-Modified attrs of %lu files were updated.", + static_cast<unsigned long>(n))); } } diff --git a/src/RequestGroup.h b/src/RequestGroup.h index 378a4876..8bc8dc22 100644 --- a/src/RequestGroup.h +++ b/src/RequestGroup.h @@ -62,7 +62,6 @@ class PreDownloadHandler; class PostDownloadHandler; class DiskWriterFactory; class Option; -class Logger; class RequestGroup; class CheckIntegrityEntry; struct DownloadResult; @@ -176,8 +175,6 @@ private: int resumeFailureCount_; - Logger* logger_; - void validateFilename(const std::string& expectedFilename, const std::string& actualFilename) const; diff --git a/src/RequestGroupMan.cc b/src/RequestGroupMan.cc index a9181afa..1b4cc68e 100644 --- a/src/RequestGroupMan.cc +++ b/src/RequestGroupMan.cc @@ -67,6 +67,7 @@ #include "Command.h" #include "FileEntry.h" #include "StringFormat.h" +#include "fmt.h" #include "FileAllocationEntry.h" #include "CheckIntegrityEntry.h" #include "Segment.h" @@ -80,20 +81,20 @@ namespace aria2 { RequestGroupMan::RequestGroupMan (const std::vector<SharedHandle<RequestGroup> >& requestGroups, unsigned int maxSimultaneousDownloads, - const Option* option): - reservedGroups_(requestGroups.begin(), requestGroups.end()), - logger_(LogFactory::getInstance()), - maxSimultaneousDownloads_(maxSimultaneousDownloads), - option_(option), - serverStatMan_(new ServerStatMan()), - maxOverallDownloadSpeedLimit_ - (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)), - maxOverallUploadSpeedLimit_(option->getAsInt(PREF_MAX_OVERALL_UPLOAD_LIMIT)), - xmlRpc_(option->getAsBool(PREF_ENABLE_XML_RPC)), - queueCheck_(true), - removedErrorResult_(0), - removedLastErrorResult_(downloadresultcode::FINISHED), - maxDownloadResult_(option->getAsInt(PREF_MAX_DOWNLOAD_RESULT)) + const Option* option) + : reservedGroups_(requestGroups.begin(), requestGroups.end()), + maxSimultaneousDownloads_(maxSimultaneousDownloads), + option_(option), + serverStatMan_(new ServerStatMan()), + maxOverallDownloadSpeedLimit_ + (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)), + maxOverallUploadSpeedLimit_(option->getAsInt + (PREF_MAX_OVERALL_UPLOAD_LIMIT)), + xmlRpc_(option->getAsBool(PREF_ENABLE_XML_RPC)), + queueCheck_(true), + removedErrorResult_(0), + removedLastErrorResult_(downloadresultcode::FINISHED), + maxDownloadResult_(option->getAsInt(PREF_MAX_DOWNLOAD_RESULT)) {} RequestGroupMan::~RequestGroupMan() {} @@ -296,9 +297,9 @@ private: // ".sig". std::string signatureFile = group->getFirstFilePath()+".sig"; if(sig->save(signatureFile)) { - logger_->notice(MSG_SIGNATURE_SAVED, signatureFile.c_str()); + A2_LOG_NOTICE(fmt(MSG_SIGNATURE_SAVED, signatureFile.c_str())); } else { - logger_->notice(MSG_SIGNATURE_NOT_SAVED, signatureFile.c_str()); + A2_LOG_NOTICE(fmt(MSG_SIGNATURE_NOT_SAVED, signatureFile.c_str())); } } } @@ -306,11 +307,11 @@ public: ProcessStoppedRequestGroup (DownloadEngine* e, std::deque<SharedHandle<DownloadResult> >& downloadResults, - std::deque<SharedHandle<RequestGroup> >& reservedGroups): - e_(e), - downloadResults_(downloadResults), - reservedGroups_(reservedGroups), - logger_(LogFactory::getInstance()) {} + std::deque<SharedHandle<RequestGroup> >& reservedGroups) + : e_(e), + downloadResults_(downloadResults), + reservedGroups_(reservedGroups) + {} void operator()(const SharedHandle<RequestGroup>& group) { @@ -341,21 +342,21 @@ public: std::vector<SharedHandle<RequestGroup> > nextGroups; group->postDownloadProcessing(nextGroups); if(!nextGroups.empty()) { - if(logger_->debug()) { - logger_->debug - ("Adding %lu RequestGroups as a result of PostDownloadHandler.", - static_cast<unsigned long>(nextGroups.size())); - } + A2_LOG_DEBUG + (fmt("Adding %lu RequestGroups as a result of" + " PostDownloadHandler.", + static_cast<unsigned long>(nextGroups.size()))); e_->getRequestGroupMan()->insertReservedGroup(0, nextGroups); } } else { - logger_->notice("Download GID#%s not complete: %s", - util::itos(group->getGID()).c_str(), - group->getDownloadContext()->getBasePath().c_str()); + A2_LOG_NOTICE + (fmt("Download GID#%s not complete: %s", + util::itos(group->getGID()).c_str(), + group->getDownloadContext()->getBasePath().c_str())); group->saveControlFile(); } } catch(RecoverableException& ex) { - logger_->error(EX_EXCEPTION_CAUGHT, ex); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex); } if(group->isPauseRequested()) { reservedGroups_.push_front(group); @@ -454,10 +455,8 @@ void RequestGroupMan::removeStoppedGroup(DownloadEngine* e) size_t numRemoved = numPrev-requestGroups_.size(); if(numRemoved > 0) { - if(logger_->debug()) { - logger_->debug("%lu RequestGroup(s) deleted.", - static_cast<unsigned long>(numRemoved)); - } + A2_LOG_DEBUG(fmt("%lu RequestGroup(s) deleted.", + static_cast<unsigned long>(numRemoved))); } } @@ -521,15 +520,11 @@ void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e) util::executeHookByOptName (groupToAdd, e->getOption(), PREF_ON_DOWNLOAD_START); } catch(RecoverableException& ex) { - logger_->error(EX_EXCEPTION_CAUGHT, ex); - if(logger_->debug()) { - logger_->debug("Deleting temporal commands."); - } + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex); + A2_LOG_DEBUG("Deleting temporal commands."); std::for_each(commands.begin(), commands.end(), Deleter()); commands.clear(); - if(logger_->debug()) { - logger_->debug("Commands deleted"); - } + A2_LOG_DEBUG("Commands deleted"); groupToAdd->releaseRuntimeResource(e); addDownloadResult(groupToAdd->createDownloadResult()); } @@ -539,9 +534,7 @@ void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e) } if(count > 0) { e->setNoWait(true); - if(logger_->debug()) { - logger_->debug("%d RequestGroup(s) added.", count); - } + A2_LOG_DEBUG(fmt("%d RequestGroup(s) added.", count)); } } @@ -556,7 +549,7 @@ void RequestGroupMan::save() try { (*itr)->saveControlFile(); } catch(RecoverableException& e) { - logger_->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } } @@ -853,14 +846,15 @@ bool RequestGroupMan::loadServerStat(const std::string& filename) { std::ifstream in(filename.c_str(), std::ios::binary); if(!in) { - logger_->error(MSG_OPENING_READABLE_SERVER_STAT_FILE_FAILED, filename.c_str()); + A2_LOG_ERROR(fmt(MSG_OPENING_READABLE_SERVER_STAT_FILE_FAILED, + filename.c_str())); return false; } if(serverStatMan_->load(in)) { - logger_->notice(MSG_SERVER_STAT_LOADED, filename.c_str()); + A2_LOG_NOTICE(fmt(MSG_SERVER_STAT_LOADED, filename.c_str())); return true; } else { - logger_->error(MSG_READING_SERVER_STAT_FILE_FAILED, filename.c_str()); + A2_LOG_ERROR(fmt(MSG_READING_SERVER_STAT_FILE_FAILED, filename.c_str())); return false; } } @@ -872,20 +866,20 @@ bool RequestGroupMan::saveServerStat(const std::string& filename) const { std::ofstream out(tempfile.c_str(), std::ios::binary); if(!out) { - logger_->error(MSG_OPENING_WRITABLE_SERVER_STAT_FILE_FAILED, - filename.c_str()); + A2_LOG_ERROR(fmt(MSG_OPENING_WRITABLE_SERVER_STAT_FILE_FAILED, + filename.c_str())); return false; } if(!serverStatMan_->save(out)) { - logger_->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str()); + A2_LOG_ERROR(fmt(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str())); return false; } } if(File(tempfile).renameTo(filename)) { - logger_->notice(MSG_SERVER_STAT_SAVED, filename.c_str()); + A2_LOG_NOTICE(fmt(MSG_SERVER_STAT_SAVED, filename.c_str())); return true; } else { - logger_->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str()); + A2_LOG_ERROR(fmt(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str())); return false; } } diff --git a/src/RequestGroupMan.h b/src/RequestGroupMan.h index dde0bb29..80e90a7f 100644 --- a/src/RequestGroupMan.h +++ b/src/RequestGroupMan.h @@ -51,7 +51,6 @@ namespace aria2 { class DownloadEngine; class Command; -class Logger; struct DownloadResult; class ServerStatMan; class ServerStat; @@ -62,7 +61,6 @@ private: std::deque<SharedHandle<RequestGroup> > requestGroups_; std::deque<SharedHandle<RequestGroup> > reservedGroups_; std::deque<SharedHandle<DownloadResult> > downloadResults_; - Logger* logger_; unsigned int maxSimultaneousDownloads_; const Option* option_; diff --git a/src/SeedCheckCommand.cc b/src/SeedCheckCommand.cc index 2ec138eb..e95c5079 100644 --- a/src/SeedCheckCommand.cc +++ b/src/SeedCheckCommand.cc @@ -37,9 +37,11 @@ #include "BtRuntime.h" #include "PieceStorage.h" #include "Logger.h" +#include "LogFactory.h" #include "SeedCriteria.h" #include "message.h" #include "RequestGroup.h" +#include "fmt.h" namespace aria2 { @@ -48,11 +50,11 @@ SeedCheckCommand::SeedCheckCommand RequestGroup* requestGroup, DownloadEngine* e, const SharedHandle<SeedCriteria>& seedCriteria) - :Command(cuid), - requestGroup_(requestGroup), - e_(e), - seedCriteria_(seedCriteria), - checkStarted_(false) + : Command(cuid), + requestGroup_(requestGroup), + e_(e), + seedCriteria_(seedCriteria), + checkStarted_(false) { setStatusRealtime(); requestGroup_->increaseNumCommand(); @@ -78,7 +80,7 @@ bool SeedCheckCommand::execute() { } if(checkStarted_) { if(seedCriteria_->evaluate()) { - getLogger()->notice(MSG_SEEDING_END); + A2_LOG_NOTICE(MSG_SEEDING_END); btRuntime_->setHalt(true); } } diff --git a/src/SegmentMan.cc b/src/SegmentMan.cc index bc668145..e75226a5 100644 --- a/src/SegmentMan.cc +++ b/src/SegmentMan.cc @@ -52,6 +52,7 @@ #include "Piece.h" #include "FileEntry.h" #include "wallclock.h" +#include "fmt.h" namespace aria2 { @@ -61,17 +62,17 @@ SegmentEntry::SegmentEntry(cuid_t cuid, const SharedHandle<Segment>& segment) SegmentEntry::~SegmentEntry() {} -SegmentMan::SegmentMan(const Option* option, - const SharedHandle<DownloadContext>& downloadContext, - const PieceStorageHandle& pieceStorage): - option_(option), - logger_(LogFactory::getInstance()), - downloadContext_(downloadContext), - pieceStorage_(pieceStorage), - lastPeerStatDlspdMapUpdated_(0), - cachedDlspd_(0), - ignoreBitfield_(downloadContext->getPieceLength(), - downloadContext->getTotalLength()) +SegmentMan::SegmentMan +(const Option* option, + const SharedHandle<DownloadContext>& downloadContext, + const PieceStorageHandle& pieceStorage) + : option_(option), + downloadContext_(downloadContext), + pieceStorage_(pieceStorage), + lastPeerStatDlspdMapUpdated_(0), + cachedDlspd_(0), + ignoreBitfield_(downloadContext->getPieceLength(), + downloadContext->getTotalLength()) { ignoreBitfield_.enableFilter(); } @@ -119,11 +120,9 @@ SharedHandle<Segment> SegmentMan::checkoutSegment if(!piece) { return SharedHandle<Segment>(); } - if(logger_->debug()) { - logger_->debug("Attach segment#%lu to CUID#%s.", + A2_LOG_DEBUG(fmt("Attach segment#%lu to CUID#%s.", static_cast<unsigned long>(piece->getIndex()), - util::itos(cuid).c_str()); - } + util::itos(cuid).c_str())); SharedHandle<Segment> segment; if(piece->getLength() == 0) { segment.reset(new GrowSegment(piece)); @@ -132,24 +131,21 @@ SharedHandle<Segment> SegmentMan::checkoutSegment } SegmentEntryHandle entry(new SegmentEntry(cuid, segment)); usedSegmentEntries_.push_back(entry); - if(logger_->debug()) { - logger_->debug("index=%lu, length=%lu, segmentLength=%lu," + A2_LOG_DEBUG(fmt("index=%lu, length=%lu, segmentLength=%lu," " writtenLength=%lu", static_cast<unsigned long>(segment->getIndex()), static_cast<unsigned long>(segment->getLength()), static_cast<unsigned long>(segment->getSegmentLength()), - static_cast<unsigned long>(segment->getWrittenLength())); - } + static_cast<unsigned long>(segment->getWrittenLength()))); if(piece->getLength() > 0) { std::map<size_t, size_t>::iterator positr = segmentWrittenLengthMemo_.find(segment->getIndex()); if(positr != segmentWrittenLengthMemo_.end()) { const size_t writtenLength = (*positr).second; - if(logger_->debug()) { - logger_->debug("writtenLength(in memo)=%lu, writtenLength=%lu", + A2_LOG_DEBUG(fmt("writtenLength(in memo)=%lu, writtenLength=%lu", static_cast<unsigned long>(writtenLength), - static_cast<unsigned long>(segment->getWrittenLength())); - } + static_cast<unsigned long>(segment->getWrittenLength())) + ); // If the difference between cached writtenLength and segment's // writtenLength is less than one block, we assume that these // missing bytes are already downloaded. @@ -255,17 +251,13 @@ SharedHandle<Segment> SegmentMan::getCleanSegmentIfOwnerIsIdle void SegmentMan::cancelSegment(const SharedHandle<Segment>& segment) { - if(logger_->debug()) { - logger_->debug("Canceling segment#%lu", - static_cast<unsigned long>(segment->getIndex())); - } + A2_LOG_DEBUG(fmt("Canceling segment#%lu", + static_cast<unsigned long>(segment->getIndex()))); pieceStorage_->cancelPiece(segment->getPiece()); segmentWrittenLengthMemo_[segment->getIndex()] = segment->getWrittenLength(); - if(logger_->debug()) { - logger_->debug("Memorized segment index=%lu, writtenLength=%lu", + A2_LOG_DEBUG(fmt("Memorized segment index=%lu, writtenLength=%lu", static_cast<unsigned long>(segment->getIndex()), - static_cast<unsigned long>(segment->getWrittenLength())); - } + static_cast<unsigned long>(segment->getWrittenLength()))); } void SegmentMan::cancelSegment(cuid_t cuid) { @@ -472,12 +464,10 @@ size_t SegmentMan::countFreePieceFrom(size_t index) const void SegmentMan::ignoreSegmentFor(const SharedHandle<FileEntry>& fileEntry) { - if(logger_->debug()) { - logger_->debug("ignoring segment for path=%s, offset=%s, length=%s", + A2_LOG_DEBUG(fmt("ignoring segment for path=%s, offset=%s, length=%s", fileEntry->getPath().c_str(), util::itos(fileEntry->getOffset()).c_str(), - util::uitos(fileEntry->getLength()).c_str()); - } + util::uitos(fileEntry->getLength()).c_str())); ignoreBitfield_.addFilter(fileEntry->getOffset(), fileEntry->getLength()); } diff --git a/src/SegmentMan.h b/src/SegmentMan.h index 41837287..8c6e6423 100644 --- a/src/SegmentMan.h +++ b/src/SegmentMan.h @@ -49,7 +49,6 @@ namespace aria2 { class Segment; -class Logger; class Option; class PeerStat; class DownloadContext; @@ -79,8 +78,6 @@ class SegmentMan { private: const Option* option_; - Logger* logger_; - SharedHandle<DownloadContext> downloadContext_; SharedHandle<PieceStorage> pieceStorage_; diff --git a/src/SelectEventPoll.cc b/src/SelectEventPoll.cc index 4297b55e..b541631d 100644 --- a/src/SelectEventPoll.cc +++ b/src/SelectEventPoll.cc @@ -45,6 +45,7 @@ #include "LogFactory.h" #include "Logger.h" #include "a2functional.h" +#include "fmt.h" namespace aria2 { @@ -149,7 +150,7 @@ void SelectEventPoll::AsyncNameResolverEntry::process #endif // ENABLE_ASYNC_DNS -SelectEventPoll::SelectEventPoll():logger_(LogFactory::getInstance()) +SelectEventPoll::SelectEventPoll() { #ifdef __MINGW32__ dummySocket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); @@ -226,11 +227,11 @@ void SelectEventPoll::poll(const struct timeval& tv) #ifdef __MINGW32__ namespace { -void checkFdCountMingw(const fd_set& fdset, Logger* logger) +void checkFdCountMingw(const fd_set& fdset) { if(fdset.fd_count >= FD_SETSIZE) { - logger->warn("The number of file descriptor exceeded FD_SETSIZE. " - "Download may slow down or fail."); + A2_LOG_WARN("The number of file descriptor exceeded FD_SETSIZE. " + "Download may slow down or fail."); } } } // namespace @@ -250,21 +251,21 @@ void SelectEventPoll::updateFdSet() sock_t fd = (*i)->getSocket(); #ifndef __MINGW32__ if(fd < 0 || FD_SETSIZE <= fd) { - logger_->warn("Detected file descriptor >= FD_SETSIZE or < 0. " - "Download may slow down or fail."); + A2_LOG_WARN("Detected file descriptor >= FD_SETSIZE or < 0. " + "Download may slow down or fail."); continue; } #endif // !__MINGW32__ int events = (*i)->getEvents(); if(events&EventPoll::EVENT_READ) { #ifdef __MINGW32__ - checkFdCountMingw(rfdset_, logger_); + checkFdCountMingw(rfdset_); #endif // __MINGW32__ FD_SET(fd, &rfdset_); } if(events&EventPoll::EVENT_WRITE) { #ifdef __MINGW32__ - checkFdCountMingw(wfdset_, logger_); + checkFdCountMingw(wfdset_); #endif // __MINGW32__ FD_SET(fd, &wfdset_); } @@ -306,9 +307,7 @@ bool SelectEventPoll::deleteEvents(sock_t socket, Command* command, updateFdSet(); return true; } else { - if(logger_->debug()) { - logger_->debug("Socket %d is not found in SocketEntries.", socket); - } + A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket)); return false; } } diff --git a/src/SelectEventPoll.h b/src/SelectEventPoll.h index 705d9eb9..739ccb2a 100644 --- a/src/SelectEventPoll.h +++ b/src/SelectEventPoll.h @@ -45,8 +45,6 @@ namespace aria2 { -class Logger; - class SelectEventPoll : public EventPoll { private: class CommandEvent { @@ -168,8 +166,6 @@ private: sock_t dummySocket_; #endif // __MINGW32__ - Logger* logger_; - void updateFdSet(); public: SelectEventPoll(); diff --git a/src/ServerStat.cc b/src/ServerStat.cc index a73771b8..c841059a 100644 --- a/src/ServerStat.cc +++ b/src/ServerStat.cc @@ -38,7 +38,9 @@ #include <algorithm> #include "array_fun.h" +#include "Logger.h" #include "LogFactory.h" +#include "fmt.h" namespace aria2 { @@ -48,15 +50,13 @@ const std::string ServerStat::STATUS_STRING[] = { }; ServerStat::ServerStat(const std::string& hostname, const std::string& protocol) - : - hostname_(hostname), - protocol_(protocol), - downloadSpeed_(0), - singleConnectionAvgSpeed_(0), - multiConnectionAvgSpeed_(0), - counter_(0), - logger_(LogFactory::getInstance()), - status_(OK) + : hostname_(hostname), + protocol_(protocol), + downloadSpeed_(0), + singleConnectionAvgSpeed_(0), + multiConnectionAvgSpeed_(0), + counter_(0), + status_(OK) {} ServerStat::~ServerStat() {} @@ -101,20 +101,17 @@ void ServerStat::updateSingleConnectionAvgSpeed(unsigned int downloadSpeed) ((1.0/5.0)*(float)downloadSpeed); } if(avgDownloadSpeed < (int)(0.80*singleConnectionAvgSpeed_)) { - if(logger_->debug()) { - logger_->debug("ServerStat:%s: resetting counter since single connection" - " speed dropped", getHostname().c_str()); - } + A2_LOG_DEBUG(fmt("ServerStat:%s: resetting counter since single connection" + " speed dropped", + getHostname().c_str())); counter_ = 0; } - if(logger_->debug()) { - logger_->debug("ServerStat:%s: singleConnectionAvgSpeed_ old:%.2fKB/s" + A2_LOG_DEBUG(fmt("ServerStat:%s: singleConnectionAvgSpeed_ old:%.2fKB/s" " new:%.2fKB/s last:%.2fKB/s", getHostname().c_str(), (float) singleConnectionAvgSpeed_/1024, (float) avgDownloadSpeed/1024, - (float) downloadSpeed / 1024); - } + (float) downloadSpeed / 1024)); singleConnectionAvgSpeed_ = (int)avgDownloadSpeed; } @@ -138,14 +135,12 @@ void ServerStat::updateMultiConnectionAvgSpeed(unsigned int downloadSpeed) avgDownloadSpeed = ((4.0/5.0)*(float)multiConnectionAvgSpeed_) + ((1.0/5.0)*(float)downloadSpeed); } - if(logger_->debug()) { - logger_->debug("ServerStat:%s: multiConnectionAvgSpeed_ old:%.2fKB/s" + A2_LOG_DEBUG(fmt("ServerStat:%s: multiConnectionAvgSpeed_ old:%.2fKB/s" " new:%.2fKB/s last:%.2fKB/s", getHostname().c_str(), (float) multiConnectionAvgSpeed_/1024, (float) avgDownloadSpeed/1024, - (float) downloadSpeed / 1024); - } + (float) downloadSpeed / 1024)); multiConnectionAvgSpeed_ = (int)avgDownloadSpeed; } @@ -176,11 +171,10 @@ void ServerStat::setStatus(const std::string& status) void ServerStat::setStatusInternal(STATUS status) { - if(logger_->debug()) { - logger_->debug("ServerStat: set status %s for %s (%s)", + A2_LOG_DEBUG(fmt("ServerStat: set status %s for %s (%s)", STATUS_STRING[status].c_str(), - hostname_.c_str(), protocol_.c_str()); - } + hostname_.c_str(), + protocol_.c_str())); status_ = status; lastUpdated_.reset(); } diff --git a/src/ServerStat.h b/src/ServerStat.h index 8cb699d9..f572997a 100644 --- a/src/ServerStat.h +++ b/src/ServerStat.h @@ -43,8 +43,6 @@ namespace aria2 { -class Logger; - // ServerStatMan: has many ServerStat // URISelector: interface // ServerStatURISelector: Has a reference of ServerStatMan @@ -160,8 +158,6 @@ private: unsigned int counter_; - Logger* logger_; - STATUS status_; Time lastUpdated_; diff --git a/src/SimpleBtMessage.cc b/src/SimpleBtMessage.cc index e542b37e..eb93384f 100644 --- a/src/SimpleBtMessage.cc +++ b/src/SimpleBtMessage.cc @@ -37,12 +37,15 @@ #include "Peer.h" #include "PeerConnection.h" #include "Logger.h" +#include "LogFactory.h" #include "util.h" +#include "fmt.h" namespace aria2 { -SimpleBtMessage::SimpleBtMessage(uint8_t id, const std::string& name): - AbstractBtMessage(id, name) {} +SimpleBtMessage::SimpleBtMessage(uint8_t id, const std::string& name) + : AbstractBtMessage(id, name) +{} void SimpleBtMessage::send() { if(isInvalidate()) { @@ -52,19 +55,15 @@ void SimpleBtMessage::send() { return; } if(!isSendingInProgress()) { - if(getLogger()->info()) { - getLogger()->info(MSG_SEND_PEER_MESSAGE, - util::itos(getCuid()).c_str(), - getPeer()->getIPAddress().c_str(), - getPeer()->getPort(), - toString().c_str()); - } + A2_LOG_INFO(fmt(MSG_SEND_PEER_MESSAGE, + util::itos(getCuid()).c_str(), + getPeer()->getIPAddress().c_str(), + getPeer()->getPort(), + toString().c_str())); unsigned char* msg = createMessage(); size_t msgLength = getMessageLength(); - if(getLogger()->debug()) { - getLogger()->debug("msglength = %lu bytes", - static_cast<unsigned long>(msgLength)); - } + A2_LOG_DEBUG(fmt("msglength = %lu bytes", + static_cast<unsigned long>(msgLength))); getPeerConnection()->pushBytes(msg, msgLength); } getPeerConnection()->sendPendingData(); diff --git a/src/SimpleLogFormatter.cc b/src/SimpleLogFormatter.cc deleted file mode 100644 index f15557a1..00000000 --- a/src/SimpleLogFormatter.cc +++ /dev/null @@ -1,96 +0,0 @@ -/* <!-- copyright */ -/* - * aria2 - The high speed download utility - * - * Copyright (C) 2010 Tatsuhiro Tsujikawa - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * In addition, as a special exception, the copyright holders give - * permission to link the code of portions of this program with the - * OpenSSL library under certain conditions as described in each - * individual source file, and distribute linked combinations - * including the two. - * You must obey the GNU General Public License in all respects - * for all of the code used other than OpenSSL. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you - * do not wish to do so, delete this exception statement from your - * version. If you delete this exception statement from all source - * files in the program, then also delete it here. - */ -/* copyright --> */ -#include "SimpleLogFormatter.h" - -#include <cassert> -#include <ostream> - -#include "util.h" -#include "a2time.h" -#include "A2STR.h" -#include "StringFormat.h" -#include "Exception.h" - -namespace aria2 { - -SimpleLogFormatter::SimpleLogFormatter() {} - -SimpleLogFormatter::~SimpleLogFormatter() {} - -namespace { -void writeHeader -(std::ostream& o, const std::string& date, const std::string& logLevelLabel) -{ - o << StringFormat("%s %s - ", date.c_str(), logLevelLabel.c_str()); -} -} // namespace - -void SimpleLogFormatter::writeLog -(std::ostream& o, Logger::LEVEL level, const std::string& logLevelLabel, - const char* msg, va_list ap) -{ - struct timeval tv; - gettimeofday(&tv, 0); - char datestr[27]; // 'YYYY-MM-DD hh:mm:ss.uuuuuu'+'\0' = 27 bytes - struct tm tm; - //tv.tv_sec may not be of type time_t. - time_t timesec = tv.tv_sec; - localtime_r(×ec, &tm); - size_t dateLength = - strftime(datestr, sizeof(datestr), "%Y-%m-%d %H:%M:%S", &tm); - assert(dateLength <= (size_t)20); - snprintf(datestr+dateLength, sizeof(datestr)-dateLength, - ".%06ld", tv.tv_usec); - writeHeader(o, datestr, logLevelLabel); - { - char buf[1024]; - std::string body = util::replace(msg, A2STR::CR_C, A2STR::NIL); - body += A2STR::LF_C; - if(vsnprintf(buf, sizeof(buf), body.c_str(), ap) < 0) { - o << "SimpleLogger error, failed to format message.\n"; - } else { - o << buf; - } - } -} - -void SimpleLogFormatter::writeStackTrace -(std::ostream& o, Logger::LEVEL level, const std::string& logLevelLabel, - const Exception& e) -{ - o << e.stackTrace(); -} - -} // namespace aria2 diff --git a/src/SingleFileAllocationIterator.cc b/src/SingleFileAllocationIterator.cc index 96d91f76..420ff699 100644 --- a/src/SingleFileAllocationIterator.cc +++ b/src/SingleFileAllocationIterator.cc @@ -49,12 +49,13 @@ namespace aria2 { #define ALIGNMENT 512 SingleFileAllocationIterator::SingleFileAllocationIterator -(BinaryStream* stream, off_t offset, uint64_t totalLength): - stream_(stream), - offset_(offset), - totalLength_(totalLength), - buffer_(0), - logger_(LogFactory::getInstance()) +(BinaryStream* stream, + off_t offset, + uint64_t totalLength) + : stream_(stream), + offset_(offset), + totalLength_(totalLength), + buffer_(0) { if(offset_%ALIGNMENT != 0) { stream_->disableDirectIO(); @@ -75,9 +76,9 @@ void SingleFileAllocationIterator::init() static bool noticeDone = false; if(!noticeDone) { noticeDone = true; - logger_->notice("Allocating disk space. Use --file-allocation=none to" - " disable it. See --file-allocation option in man page for" - " more details."); + A2_LOG_NOTICE("Allocating disk space. Use --file-allocation=none to" + " disable it. See --file-allocation option in man page for" + " more details."); } #ifdef HAVE_POSIX_MEMALIGN buffer_ = reinterpret_cast<unsigned char*> diff --git a/src/SingleFileAllocationIterator.h b/src/SingleFileAllocationIterator.h index 68cc57cc..a3d12602 100644 --- a/src/SingleFileAllocationIterator.h +++ b/src/SingleFileAllocationIterator.h @@ -40,7 +40,6 @@ namespace aria2 { class BinaryStream; -class Logger; class SingleFileAllocationIterator:public FileAllocationIterator { @@ -52,8 +51,6 @@ private: uint64_t totalLength_; unsigned char* buffer_; - - Logger* logger_; public: SingleFileAllocationIterator(BinaryStream* stream, off_t offset, uint64_t totalLength); diff --git a/src/SocketCore.cc b/src/SocketCore.cc index f735ec01..95cc5e96 100644 --- a/src/SocketCore.cc +++ b/src/SocketCore.cc @@ -50,6 +50,7 @@ #include "DlRetryEx.h" #include "DlAbortEx.h" #include "StringFormat.h" +#include "fmt.h" #include "util.h" #include "TimeA2.h" #include "a2functional.h" @@ -130,11 +131,17 @@ void SocketCore::setTLSContext(const SharedHandle<TLSContext>& tlsContext) } #endif // ENABLE_SSL -SocketCore::SocketCore(int sockType):sockType_(sockType), sockfd_(-1) { +SocketCore::SocketCore(int sockType) + : sockType_(sockType), + sockfd_(-1) +{ init(); } -SocketCore::SocketCore(sock_t sockfd, int sockType):sockType_(sockType), sockfd_(sockfd) { +SocketCore::SocketCore(sock_t sockfd, int sockType) + : sockType_(sockType), + sockfd_(sockfd) +{ init(); } @@ -431,9 +438,7 @@ void SocketCore::establishConnection(const std::string& host, uint16_t port) (*i).second) == -1) { errNum = SOCKET_ERRNO; error = errorMsg(errNum); - if(LogFactory::getInstance()->debug()) { - LogFactory::getInstance()->debug(EX_SOCKET_BIND, error.c_str()); - } + A2_LOG_DEBUG(fmt(EX_SOCKET_BIND, error.c_str())); } else { bindSuccess = true; break; @@ -1274,9 +1279,7 @@ void SocketCore::bindAddress(const std::string& iface) host, NI_MAXHOST, 0, 0, NI_NUMERICHOST); if(s == 0) { - if(LogFactory::getInstance()->debug()) { - LogFactory::getInstance()->debug("Sockets will bind to %s", host); - } + A2_LOG_DEBUG(fmt("Sockets will bind to %s", host)); } } } @@ -1286,17 +1289,14 @@ void getInterfaceAddress (std::vector<std::pair<struct sockaddr_storage, socklen_t> >& ifAddrs, const std::string& iface, int family, int aiFlags) { - Logger* logger = LogFactory::getInstance(); - if(logger->debug()) { - logger->debug("Finding interface %s", iface.c_str()); - } + A2_LOG_DEBUG(fmt("Finding interface %s", iface.c_str())); #ifdef HAVE_GETIFADDRS // First find interface in interface addresses struct ifaddrs* ifaddr = 0; if(getifaddrs(&ifaddr) == -1) { int errNum = SOCKET_ERRNO; - logger->info(MSG_INTERFACE_NOT_FOUND, - iface.c_str(), errorMsg(errNum).c_str()); + A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND, + iface.c_str(), errorMsg(errNum).c_str())); } else { auto_delete<struct ifaddrs*> ifaddrDeleter(ifaddr, freeifaddrs); for(struct ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) { @@ -1335,7 +1335,7 @@ void getInterfaceAddress int s; s = callGetaddrinfo(&res, iface.c_str(), 0, family, SOCK_STREAM, aiFlags,0); if(s) { - logger->info(MSG_INTERFACE_NOT_FOUND, iface.c_str(), gai_strerror(s)); + A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), gai_strerror(s))); } else { WSAAPI_AUTO_DELETE<struct addrinfo*> resDeleter(res, freeaddrinfo); struct addrinfo* rp; diff --git a/src/TimedHaltCommand.cc b/src/TimedHaltCommand.cc index ab36a110..1962b812 100644 --- a/src/TimedHaltCommand.cc +++ b/src/TimedHaltCommand.cc @@ -36,15 +36,19 @@ #include "DownloadEngine.h" #include "RequestGroupMan.h" #include "Logger.h" +#include "LogFactory.h" #include "message.h" +#include "fmt.h" namespace aria2 { -TimedHaltCommand::TimedHaltCommand(cuid_t cuid, DownloadEngine* e, - time_t secondsToHalt, - bool forceHalt): - TimeBasedCommand(cuid, e, secondsToHalt, true), - forceHalt_(forceHalt) {} +TimedHaltCommand::TimedHaltCommand +(cuid_t cuid, DownloadEngine* e, + time_t secondsToHalt, + bool forceHalt) + : TimeBasedCommand(cuid, e, secondsToHalt, true), + forceHalt_(forceHalt) +{} TimedHaltCommand::~TimedHaltCommand() {} @@ -59,10 +63,10 @@ void TimedHaltCommand::preProcess() void TimedHaltCommand::process() { if(!getDownloadEngine()->isHaltRequested()) { - getLogger()->notice(MSG_TIME_HAS_PASSED, - static_cast<long int>(getInterval())); + A2_LOG_NOTICE(fmt(MSG_TIME_HAS_PASSED, + static_cast<long int>(getInterval()))); if(forceHalt_) { - getLogger()->notice("This is emergency shutdown."); + A2_LOG_NOTICE("This is emergency shutdown."); getDownloadEngine()->requestForceHalt(); } else { getDownloadEngine()->requestHalt(); diff --git a/src/TrackerWatcherCommand.cc b/src/TrackerWatcherCommand.cc index e20bcf88..6cd07c62 100644 --- a/src/TrackerWatcherCommand.cc +++ b/src/TrackerWatcherCommand.cc @@ -53,6 +53,7 @@ #include "Option.h" #include "DlAbortEx.h" #include "Logger.h" +#include "LogFactory.h" #include "A2STR.h" #include "SocketCore.h" #include "Request.h" @@ -61,14 +62,15 @@ #include "bittorrent_helper.h" #include "a2functional.h" #include "util.h" +#include "fmt.h" namespace aria2 { TrackerWatcherCommand::TrackerWatcherCommand -(cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e): - Command(cuid), - requestGroup_(requestGroup), - e_(e) +(cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e) + : Command(cuid), + requestGroup_(requestGroup), + e_(e) { requestGroup_->increaseNumCommand(); } @@ -92,9 +94,7 @@ bool TrackerWatcherCommand::execute() { } } if(btAnnounce_->noMoreAnnounce()) { - if(getLogger()->debug()) { - getLogger()->debug("no more announce"); - } + A2_LOG_DEBUG("no more announce"); return true; } if(!trackerRequestGroup_) { @@ -106,11 +106,9 @@ bool TrackerWatcherCommand::execute() { trackerRequestGroup_->createInitialCommand(*commands, e_); e_->addCommand(*commands); commands->clear(); - if(getLogger()->debug()) { - getLogger()->debug("added tracker request command"); - } + A2_LOG_DEBUG("added tracker request command"); } catch(RecoverableException& ex) { - getLogger()->error(EX_EXCEPTION_CAUGHT, ex); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex); } } } else if(trackerRequestGroup_->downloadFinished()){ @@ -121,7 +119,7 @@ bool TrackerWatcherCommand::execute() { btAnnounce_->announceSuccess(); btAnnounce_->resetAnnounce(); } catch(RecoverableException& ex) { - getLogger()->error(EX_EXCEPTION_CAUGHT, ex); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex); btAnnounce_->announceFailure(); if(btAnnounce_->isAllAnnounceFailed()) { btAnnounce_->resetAnnounce(); @@ -176,11 +174,9 @@ void TrackerWatcherCommand::processTrackerResponse command->setPeerStorage(peerStorage_); command->setPieceStorage(pieceStorage_); e_->addCommand(command); - if(getLogger()->debug()) { - getLogger()->debug("CUID#%s - Adding new command CUID#%s", - util::itos(getCuid()).c_str(), - util::itos(peer->usedBy()).c_str()); - } + A2_LOG_DEBUG(fmt("CUID#%s - Adding new command CUID#%s", + util::itos(getCuid()).c_str(), + util::itos(peer->usedBy()).c_str())); } } @@ -220,13 +216,9 @@ TrackerWatcherCommand::createRequestGroup(const std::string& uri) uris.push_back(uri); SharedHandle<RequestGroup> rg(new RequestGroup(getOption())); if(backupTrackerIsAvailable(requestGroup_->getDownloadContext())) { - if(getLogger()->debug()) { - getLogger()->debug("This is multi-tracker announce."); - } + A2_LOG_DEBUG("This is multi-tracker announce."); } else { - if(getLogger()->debug()) { - getLogger()->debug("This is single-tracker announce."); - } + A2_LOG_DEBUG("This is single-tracker announce."); } rg->setNumConcurrentCommand(1); // If backup tracker is available, try 2 times for each tracker @@ -254,10 +246,8 @@ TrackerWatcherCommand::createRequestGroup(const std::string& uri) rg->setFileAllocationEnabled(false); rg->setPreLocalFileCheckEnabled(false); util::removeMetalinkContentTypes(rg); - if(getLogger()->info()) { - getLogger()->info("Creating tracker request group GID#%s", - util::itos(rg->getGID()).c_str()); - } + A2_LOG_INFO(fmt("Creating tracker request group GID#%s", + util::itos(rg->getGID()).c_str())); return rg; } diff --git a/src/UTMetadataDataExtensionMessage.cc b/src/UTMetadataDataExtensionMessage.cc index 75166108..93cf0a62 100644 --- a/src/UTMetadataDataExtensionMessage.cc +++ b/src/UTMetadataDataExtensionMessage.cc @@ -45,15 +45,18 @@ #include "bittorrent_helper.h" #include "DiskAdaptor.h" #include "Piece.h" +#include "Logger.h" #include "LogFactory.h" #include "DlAbortEx.h" +#include "fmt.h" namespace aria2 { UTMetadataDataExtensionMessage::UTMetadataDataExtensionMessage -(uint8_t extensionMessageID):UTMetadataExtensionMessage(extensionMessageID), - tracker_(0), - logger_(LogFactory::getInstance()) {} +(uint8_t extensionMessageID) + : UTMetadataExtensionMessage(extensionMessageID), + tracker_(0) +{} UTMetadataDataExtensionMessage::~UTMetadataDataExtensionMessage() {} @@ -74,10 +77,8 @@ std::string UTMetadataDataExtensionMessage::toString() const void UTMetadataDataExtensionMessage::doReceivedAction() { if(tracker_->tracks(getIndex())) { - if(logger_->debug()) { - logger_->debug("ut_metadata index=%lu found in tracking list", - static_cast<unsigned long>(getIndex())); - } + A2_LOG_DEBUG(fmt("ut_metadata index=%lu found in tracking list", + static_cast<unsigned long>(getIndex()))); tracker_->remove(getIndex()); pieceStorage_->getDiskAdaptor()->writeData (reinterpret_cast<const unsigned char*>(data_.c_str()), data_.size(), @@ -91,9 +92,9 @@ void UTMetadataDataExtensionMessage::doReceivedAction() metadata.data(), metadata.size()); if(memcmp(infoHash, bittorrent::getInfoHash(dctx_), INFO_HASH_LENGTH) == 0) { - logger_->info("Got ut_metadata"); + A2_LOG_INFO("Got ut_metadata"); } else { - logger_->info("Got wrong ut_metadata"); + A2_LOG_INFO("Got wrong ut_metadata"); for(size_t i = 0; i < dctx_->getNumPieces(); ++i) { pieceStorage_->markPieceMissing(i); } @@ -101,10 +102,8 @@ void UTMetadataDataExtensionMessage::doReceivedAction() } } } else { - if(logger_->debug()) { - logger_->debug("ut_metadata index=%lu is not tracked", - static_cast<unsigned long>(getIndex())); - } + A2_LOG_DEBUG(fmt("ut_metadata index=%lu is not tracked", + static_cast<unsigned long>(getIndex()))); } } diff --git a/src/UTMetadataDataExtensionMessage.h b/src/UTMetadataDataExtensionMessage.h index e4a70862..bd5b947c 100644 --- a/src/UTMetadataDataExtensionMessage.h +++ b/src/UTMetadataDataExtensionMessage.h @@ -42,7 +42,6 @@ namespace aria2 { class DownloadContext; class PieceStorage; class UTMetadataRequestTracker; -class Logger; class UTMetadataDataExtensionMessage:public UTMetadataExtensionMessage { private: @@ -55,8 +54,6 @@ private: SharedHandle<PieceStorage> pieceStorage_; UTMetadataRequestTracker* tracker_; - - Logger* logger_; public: UTMetadataDataExtensionMessage(uint8_t extensionMessageID); diff --git a/src/UTMetadataPostDownloadHandler.cc b/src/UTMetadataPostDownloadHandler.cc index a7f72aa0..3dd9329d 100644 --- a/src/UTMetadataPostDownloadHandler.cc +++ b/src/UTMetadataPostDownloadHandler.cc @@ -49,6 +49,7 @@ #include "message.h" #include "prefs.h" #include "Option.h" +#include "fmt.h" namespace aria2 { @@ -66,8 +67,7 @@ bool UTMetadataPostDownloadHandler::Criteria::match return false; } -UTMetadataPostDownloadHandler::UTMetadataPostDownloadHandler(): - logger_(LogFactory::getInstance()) +UTMetadataPostDownloadHandler::UTMetadataPostDownloadHandler() { SharedHandle<Criteria> cri(new Criteria()); setCriteria(cri); @@ -87,9 +87,9 @@ void UTMetadataPostDownloadHandler::getNextRequestGroups util::applyDir(requestGroup->getOption()->get(PREF_DIR), util::toHex(attrs->infoHash)+".torrent"); if(util::saveAs(filename, torrent)) { - logger_->notice(MSG_METADATA_SAVED, filename.c_str()); + A2_LOG_NOTICE(fmt(MSG_METADATA_SAVED, filename.c_str())); } else { - logger_->notice(MSG_METADATA_NOT_SAVED, filename.c_str()); + A2_LOG_NOTICE(fmt(MSG_METADATA_NOT_SAVED, filename.c_str())); } } if(!requestGroup->getOption()->getAsBool(PREF_BT_METADATA_ONLY)) { diff --git a/src/UTMetadataPostDownloadHandler.h b/src/UTMetadataPostDownloadHandler.h index 0e8293ef..19364304 100644 --- a/src/UTMetadataPostDownloadHandler.h +++ b/src/UTMetadataPostDownloadHandler.h @@ -40,13 +40,9 @@ namespace aria2 { -class Logger; - class UTMetadataPostDownloadHandler:public PostDownloadHandler { private: - Logger* logger_; - class Criteria:public RequestGroupCriteria { public: diff --git a/src/UTMetadataRequestFactory.cc b/src/UTMetadataRequestFactory.cc index 40130b55..604449cf 100644 --- a/src/UTMetadataRequestFactory.cc +++ b/src/UTMetadataRequestFactory.cc @@ -41,15 +41,17 @@ #include "UTMetadataRequestExtensionMessage.h" #include "UTMetadataRequestTracker.h" #include "BtMessage.h" +#include "Logger.h" #include "LogFactory.h" +#include "fmt.h" namespace aria2 { -UTMetadataRequestFactory::UTMetadataRequestFactory(): - dispatcher_(0), - messageFactory_(0), - tracker_(0), - logger_(LogFactory::getInstance()) {} +UTMetadataRequestFactory::UTMetadataRequestFactory() + : dispatcher_(0), + messageFactory_(0), + tracker_(0) +{} void UTMetadataRequestFactory::create (std::vector<SharedHandle<BtMessage> >& msgs, size_t num, @@ -60,16 +62,12 @@ void UTMetadataRequestFactory::create SharedHandle<Piece> p = pieceStorage->getMissingPiece(peer_, metadataRequests); if(!p) { - if(logger_->debug()) { - logger_->debug("No ut_metadata piece is available to download."); - } + A2_LOG_DEBUG("No ut_metadata piece is available to download."); break; } --num; - if(logger_->debug()) { - logger_->debug("Creating ut_metadata request index=%lu", - static_cast<unsigned long>(p->getIndex())); - } + A2_LOG_DEBUG(fmt("Creating ut_metadata request index=%lu", + static_cast<unsigned long>(p->getIndex()))); SharedHandle<UTMetadataRequestExtensionMessage> m (new UTMetadataRequestExtensionMessage (peer_->getExtensionMessageID("ut_metadata"))); diff --git a/src/UTMetadataRequestFactory.h b/src/UTMetadataRequestFactory.h index a97fda98..e8e02b2a 100644 --- a/src/UTMetadataRequestFactory.h +++ b/src/UTMetadataRequestFactory.h @@ -50,7 +50,6 @@ class BtMessageDispatcher; class BtMessageFactory; class UTMetadataRequestTracker; class BtMessage; -class Logger; class UTMetadataRequestFactory { private: @@ -63,8 +62,6 @@ private: BtMessageFactory* messageFactory_; UTMetadataRequestTracker* tracker_; - - Logger* logger_; public: UTMetadataRequestFactory(); diff --git a/src/UTMetadataRequestTracker.cc b/src/UTMetadataRequestTracker.cc index 4c35e81b..d04887dc 100644 --- a/src/UTMetadataRequestTracker.cc +++ b/src/UTMetadataRequestTracker.cc @@ -36,12 +36,13 @@ #include <algorithm> +#include "Logger.h" #include "LogFactory.h" +#include "fmt.h" namespace aria2 { -UTMetadataRequestTracker::UTMetadataRequestTracker(): - logger_(LogFactory::getInstance()) {} +UTMetadataRequestTracker::UTMetadataRequestTracker() {} void UTMetadataRequestTracker::add(size_t index) { @@ -71,10 +72,8 @@ std::vector<size_t> UTMetadataRequestTracker::removeTimeoutEntry() for(std::vector<RequestEntry>::iterator i = trackedRequests_.begin(), eoi = trackedRequests_.end(); i != eoi;) { if((*i).elapsed(TIMEOUT)) { - if(logger_->debug()) { - logger_->debug("ut_metadata request timeout. index=%lu", - static_cast<unsigned long>((*i).index_)); - } + A2_LOG_DEBUG(fmt("ut_metadata request timeout. index=%lu", + static_cast<unsigned long>((*i).index_))); indexes.push_back((*i).index_); i = trackedRequests_.erase(i); eoi = trackedRequests_.end(); diff --git a/src/UTMetadataRequestTracker.h b/src/UTMetadataRequestTracker.h index fbd93770..5ba719b5 100644 --- a/src/UTMetadataRequestTracker.h +++ b/src/UTMetadataRequestTracker.h @@ -44,8 +44,6 @@ namespace aria2 { -class Logger; - class UTMetadataRequestTracker { private: struct RequestEntry { @@ -66,8 +64,6 @@ private: }; std::vector<RequestEntry> trackedRequests_; - - Logger* logger_; public: UTMetadataRequestTracker(); diff --git a/src/XmlRpcMethod.cc b/src/XmlRpcMethod.cc index 152aef70..be243d05 100644 --- a/src/XmlRpcMethod.cc +++ b/src/XmlRpcMethod.cc @@ -46,15 +46,16 @@ #include "XmlRpcResponse.h" #include "prefs.h" #include "StringFormat.h" +#include "fmt.h" #include "DlAbortEx.h" namespace aria2 { namespace xmlrpc { -XmlRpcMethod::XmlRpcMethod(): - optionParser_(OptionParser::getInstance()), - logger_(LogFactory::getInstance()) {} +XmlRpcMethod::XmlRpcMethod() + : optionParser_(OptionParser::getInstance()) +{} XmlRpcMethod::~XmlRpcMethod() {} @@ -73,9 +74,7 @@ XmlRpcResponse XmlRpcMethod::execute try { return XmlRpcResponse(0, process(req, e)); } catch(RecoverableException& e) { - if(logger_->debug()) { - logger_->debug(EX_EXCEPTION_CAUGHT, e); - } + A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, e); return XmlRpcResponse(1, createErrorResponse(e)); } } diff --git a/src/XmlRpcMethod.h b/src/XmlRpcMethod.h index 3a875ed6..cbdf65c1 100644 --- a/src/XmlRpcMethod.h +++ b/src/XmlRpcMethod.h @@ -46,7 +46,6 @@ namespace aria2 { class DownloadEngine; class OptionParser; -class Logger; class Option; class Exception; @@ -65,8 +64,6 @@ struct XmlRpcResponse; class XmlRpcMethod { private: SharedHandle<OptionParser> optionParser_; - - Logger* logger_; protected: // Subclass must implement this function to fulfil XmlRpcRequest // req. The return value of this method is used as a return value diff --git a/src/XmlRpcMethodImpl.cc b/src/XmlRpcMethodImpl.cc index efad911c..70a6e839 100644 --- a/src/XmlRpcMethodImpl.cc +++ b/src/XmlRpcMethodImpl.cc @@ -49,6 +49,7 @@ #include "util.h" #include "RequestGroupMan.h" #include "StringFormat.h" +#include "fmt.h" #include "XmlRpcRequest.h" #include "PieceStorage.h" #include "DownloadContext.h" @@ -1273,7 +1274,7 @@ SharedHandle<ValueBase> goingShutdown // Schedule shutdown after 3seconds to give time to client to // receive XML-RPC response. e->addRoutineCommand(new TimedHaltCommand(e->newCUID(), e, 3, forceHalt)); - LogFactory::getInstance()->info("Scheduled shutdown in 3 seconds."); + A2_LOG_INFO("Scheduled shutdown in 3 seconds."); return VLB_OK; } } // namespace diff --git a/src/download_helper.cc b/src/download_helper.cc index 1f2a11e6..4d313085 100644 --- a/src/download_helper.cc +++ b/src/download_helper.cc @@ -52,6 +52,7 @@ #include "DlAbortEx.h" #include "message.h" #include "StringFormat.h" +#include "fmt.h" #include "FileEntry.h" #include "LogFactory.h" #include "File.h" @@ -401,7 +402,7 @@ public: } catch(RecoverableException& e) { // error occurred while parsing torrent file. // We simply ignore it. - LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } else if(!ignoreLocalPath_ && detector_.guessTorrentFile(uri)) { try { @@ -410,7 +411,7 @@ public: } catch(RecoverableException& e) { // error occurred while parsing torrent file. // We simply ignore it. - LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } #endif // ENABLE_BITTORRENT @@ -421,12 +422,12 @@ public: } catch(RecoverableException& e) { // error occurred while parsing metalink file. // We simply ignore it. - LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e); + A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } #endif // ENABLE_METALINK else { - LogFactory::getInstance()->error(MSG_UNRECOGNIZED_URI, (uri).c_str()); + A2_LOG_ERROR(fmt(MSG_UNRECOGNIZED_URI, (uri).c_str())); } } }; diff --git a/src/SimpleLogFormatter.h b/src/fmt.cc index 5819a500..a4e97330 100644 --- a/src/SimpleLogFormatter.h +++ b/src/fmt.cc @@ -32,28 +32,24 @@ * files in the program, then also delete it here. */ /* copyright --> */ -#ifndef D_SIMPLE_LOG_FORMATTER_H -#define D_SIMPLE_LOG_FORMATTER_H +#include "fmt.h" -#include "LogFormatter.h" +#include <cstring> +#include <cstdio> +#include <cstdlib> namespace aria2 { -class SimpleLogFormatter:public LogFormatter { -public: - SimpleLogFormatter(); - - virtual ~SimpleLogFormatter(); - - virtual void writeLog - (std::ostream& o, Logger::LEVEL logLevel, const std::string& logLevelLabel, - const char* msg, va_list ap); - - virtual void writeStackTrace - (std::ostream& o, Logger::LEVEL logLevel, const std::string& logLevelLabel, - const Exception& e); -}; +std::string fmt(const char* fmtTemplate, ...) +{ + va_list ap; + va_start(ap, fmtTemplate); + char buf[1024]; + if(vsnprintf(buf, sizeof(buf), fmtTemplate, ap) <= 0) { + buf[0] = '\0'; + } + va_end(ap); + return buf; +} } // namespace aria2 - -#endif // D_SIMPLE_LOG_FORMATTER_H diff --git a/src/LogFormatter.h b/src/fmt.h index 7f872298..e94ecb26 100644 --- a/src/LogFormatter.h +++ b/src/fmt.h @@ -32,34 +32,18 @@ * files in the program, then also delete it here. */ /* copyright --> */ -#ifndef D_LOG_FORMATTER_H -#define D_LOG_FORMATTER_H +#ifndef D_FMT_H +#define D_FMT_H #include "common.h" -#include <cstdarg> -#include <iosfwd> #include <string> - -#include "Logger.h" +#include <cstdarg> namespace aria2 { -class Exception; - -class LogFormatter { -public: - virtual ~LogFormatter() {} - - virtual void writeLog - (std::ostream& o, Logger::LEVEL logLevel, const std::string& logLevelLabel, - const char* msg, va_list ap) = 0; - - virtual void writeStackTrace - (std::ostream& o, Logger::LEVEL logLevel, const std::string& logLevelLabel, - const Exception& ex) = 0; -}; +std::string fmt(const char* fmt, ...) __attribute__ ((format (printf, 1, 2))); } // namespace aria2 -#endif // D_LOG_FORMATTER_H +#endif // D_FMT_H diff --git a/src/main.cc b/src/main.cc index a5091e03..dfc57b4d 100644 --- a/src/main.cc +++ b/src/main.cc @@ -68,6 +68,7 @@ #include "RecoverableException.h" #include "SocketCore.h" #include "DownloadContext.h" +#include "fmt.h" #ifdef ENABLE_BITTORRENT # include "bittorrent_helper.h" #endif // ENABLE_BITTORRENT @@ -187,12 +188,11 @@ downloadresultcode::RESULT main(int argc, char* argv[]) LogFactory::setConsoleOutput(false); } downloadresultcode::RESULT exitStatus = downloadresultcode::FINISHED; - Logger* logger = LogFactory::getInstance(); - logger->info("<<--- --- --- ---"); - logger->info(" --- --- --- ---"); - logger->info(" --- --- --- --->>"); - logger->info("%s %s %s", PACKAGE, PACKAGE_VERSION, TARGET); - logger->info(MSG_LOGGING_STARTED); + A2_LOG_INFO("<<--- --- --- ---"); + A2_LOG_INFO(" --- --- --- ---"); + A2_LOG_INFO(" --- --- --- --->>"); + A2_LOG_INFO(fmt("%s %s %s", PACKAGE, PACKAGE_VERSION, TARGET)); + A2_LOG_INFO(MSG_LOGGING_STARTED); #ifdef ENABLE_MESSAGE_DIGEST MessageDigestHelper::staticSHA1DigestInit(); diff --git a/src/util.cc b/src/util.cc index 281bda4f..b42ac20b 100644 --- a/src/util.cc +++ b/src/util.cc @@ -72,12 +72,14 @@ #include "FatalException.h" #include "FileEntry.h" #include "StringFormat.h" +#include "fmt.h" #include "A2STR.h" #include "array_fun.h" #include "bitfield.h" #include "DownloadHandlerConstants.h" #include "RequestGroup.h" #include "LogFactory.h" +#include "Logger.h" #include "Option.h" #ifdef ENABLE_MESSAGE_DIGEST # include "MessageDigest.h" @@ -1451,13 +1453,13 @@ void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group) void executeHook(const std::string& command, const std::string& arg) { - LogFactory::getInstance()->info("Executing user command: %s %s", - command.c_str(), arg.c_str()); + A2_LOG_INFO(fmt("Executing user command: %s %s", + command.c_str(), + arg.c_str())); #ifndef __MINGW32__ pid_t cpid = fork(); if(cpid == -1) { - LogFactory::getInstance()->error("fork() failed." - " Cannot execute user command."); + A2_LOG_ERROR("fork() failed. Cannot execute user command."); } else if(cpid == 0) { execl(command.c_str(), command.c_str(), arg.c_str(), reinterpret_cast<char*>(0)); @@ -1488,9 +1490,9 @@ void executeHook(const std::string& command, const std::string& arg) &si, &pi); - if(!rc) - LogFactory::getInstance()->error("CreateProcess() failed." - " Cannot execute user command."); + if(!rc) { + A2_LOG_ERROR("CreateProcess() failed. Cannot execute user command."); + } #endif } |
