[Libreoffice-commits] online.git: Branch 'distro/collabora/collabora-online-1-9' - 51 commits - loleaflet/main.js loleaflet/src loolwsd/AdminModel.cpp loolwsd/ChildSession.cpp loolwsd/Common.hpp loolwsd/DocumentBroker.cpp loolwsd/DocumentBroker.hpp loolwsd/IoUtil.cpp loolwsd/LibreOfficeKit.hpp loolwsd/Log.hpp loolwsd/LOOLKit.cpp loolwsd/LOOLProtocol.hpp loolwsd/LOOLSession.cpp loolwsd/LOOLSession.hpp loolwsd/LOOLWSD.cpp loolwsd/loolwsd.spec.in loolwsd/maketarballfordeb.sh.in loolwsd/PrisonerSession.cpp loolwsd/protocol.txt loolwsd/Storage.cpp loolwsd/test loolwsd/Unit.cpp loolwsd/Util.cpp

Andras Timar andras.timar at collabora.com
Mon Nov 7 14:21:47 UTC 2016


 loleaflet/main.js                        |    5 
 loleaflet/src/control/Control.Menubar.js |   36 ++
 loleaflet/src/core/LOUtil.js             |    2 
 loleaflet/src/core/Socket.js             |    4 
 loleaflet/src/map/Map.js                 |    4 
 loolwsd/AdminModel.cpp                   |    2 
 loolwsd/ChildSession.cpp                 |   41 +-
 loolwsd/Common.hpp                       |    2 
 loolwsd/DocumentBroker.cpp               |  414 ++++++++++++++--------------
 loolwsd/DocumentBroker.hpp               |   67 +++-
 loolwsd/IoUtil.cpp                       |    2 
 loolwsd/LOOLKit.cpp                      |  315 +++++++++++----------
 loolwsd/LOOLProtocol.hpp                 |    2 
 loolwsd/LOOLSession.cpp                  |   45 +--
 loolwsd/LOOLSession.hpp                  |    6 
 loolwsd/LOOLWSD.cpp                      |  446 +++++++++++++++----------------
 loolwsd/LibreOfficeKit.hpp               |    9 
 loolwsd/Log.hpp                          |   13 
 loolwsd/PrisonerSession.cpp              |   24 -
 loolwsd/Storage.cpp                      |   59 ++--
 loolwsd/Unit.cpp                         |    6 
 loolwsd/Util.cpp                         |    7 
 loolwsd/loolwsd.spec.in                  |    2 
 loolwsd/maketarballfordeb.sh.in          |    7 
 loolwsd/protocol.txt                     |    4 
 loolwsd/test/TileCacheTests.cpp          |   14 
 loolwsd/test/UnitPrefork.cpp             |   17 -
 loolwsd/test/UnitStorage.cpp             |    3 
 loolwsd/test/helpers.hpp                 |   27 +
 loolwsd/test/httpwstest.cpp              |    9 
 loolwsd/test/run_unit.sh.in              |    5 
 31 files changed, 868 insertions(+), 731 deletions(-)

New commits:
commit 4a94a41781c8d8dd0a7da431044af885d6793f51
Author: Andras Timar <andras.timar at collabora.com>
Date:   Mon Nov 7 15:20:01 2016 +0100

    loolwsd: copy 'debian' dir to tarball, silence tar
    
    (cherry picked from commit f6a694716cc15451486dee5006cd0e6e9c05a44e)

diff --git a/loolwsd/maketarballfordeb.sh.in b/loolwsd/maketarballfordeb.sh.in
index 2ecd183..3000455 100755
--- a/loolwsd/maketarballfordeb.sh.in
+++ b/loolwsd/maketarballfordeb.sh.in
@@ -3,11 +3,12 @@
 TEMPDIR=`mktemp -d`
 SRCDIR=`pwd`
 cd $TEMPDIR
-tar xzvf $SRCDIR/loolwsd- at PACKAGE_VERSION@.tar.gz
+tar xzf $SRCDIR/loolwsd- at PACKAGE_VERSION@.tar.gz
+cp -a $SRCDIR/debian loolwsd- at PACKAGE_VERSION@
 mkdir loolwsd- at PACKAGE_VERSION@/loleaflet
 cd loolwsd- at PACKAGE_VERSION@/loleaflet
-tar xzvf $SRCDIR/../loleaflet/loleaflet- at PACKAGE_VERSION@.tar.gz --strip-components=1
+tar xzf $SRCDIR/../loleaflet/loleaflet- at PACKAGE_VERSION@.tar.gz --strip-components=1
 cd $TEMPDIR
-tar czvf $SRCDIR/loolwsd_ at PACKAGE_VERSION@.orig.tar.gz loolwsd- at PACKAGE_VERSION@
+tar czf $SRCDIR/loolwsd_ at PACKAGE_VERSION@.orig.tar.gz loolwsd- at PACKAGE_VERSION@
 cd $SRCDIR
 rm -rf $TEMPDIR
commit 75b253d0e4e46afb4a22eded0b07ebfb168393ed
Author: Pranav Kant <pranavk at collabora.co.uk>
Date:   Mon Nov 7 17:59:42 2016 +0530

    Fix menubar l10n, set String.locale before requiring loleaflet
    
    Change-Id: Ic5a22f05d0a11bd0485d0c88dfa34dcc6bfe29cf
    (cherry picked from commit 5f9a9264e4c824a805c182b061f11a9869123fe1)

diff --git a/loleaflet/main.js b/loleaflet/main.js
index 3528ea9..831e6bf 100644
--- a/loleaflet/main.js
+++ b/loleaflet/main.js
@@ -30,8 +30,6 @@ global.vex = vex;
 
 global.devtools = require('devtools-detect');
 var errorMessages = require('./dist/errormessages');
-var L = require('loleaflet');
-require('./dist/plugins/draw-0.2.4/dist/leaflet.draw.js');
 
 function getParameterByName(name) {
     name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
@@ -44,6 +42,9 @@ if (lang) {
     String.locale = lang;
 }
 
+var L = require('loleaflet');
+require('./dist/plugins/draw-0.2.4/dist/leaflet.draw.js');
+
 var wopiSrc = getParameterByName('WOPISrc');
 
 if (wopiSrc !== '' && access_token !== '') {
commit 7c2c3b64e69a98bf9bab914faaa5fc81f308bd84
Author: Pranav Kant <pranavk at collabora.co.uk>
Date:   Mon Nov 7 17:11:26 2016 +0530

    getViewIdHexColor -> getViewIdColor
    
    This doesn't return a hex value anymore, it returns a rgb
    integer.
    
    Change-Id: I2fc234d7ba09e7b750c63dd9cf93356d02707fce
    (cherry picked from commit 9f65377c424ab9316e184103e28a7ab77b2b8456)

diff --git a/loleaflet/src/core/LOUtil.js b/loleaflet/src/core/LOUtil.js
index ed6b718..422e65b 100644
--- a/loleaflet/src/core/LOUtil.js
+++ b/loleaflet/src/core/LOUtil.js
@@ -43,7 +43,7 @@ L.LOUtil = {
 		return spinnerInterval;
 	},
 
-	getViewIdHexColor: function(viewId) {
+	getViewIdColor: function(viewId) {
 		var color = this.darkColors[(viewId + 1) % this.darkColors.length];
 		return (color[2] | (color[1] << 8) | (color[0] << 16));
 	},
diff --git a/loleaflet/src/map/Map.js b/loleaflet/src/map/Map.js
index be634aa..46c53ee 100644
--- a/loleaflet/src/map/Map.js
+++ b/loleaflet/src/map/Map.js
@@ -157,7 +157,7 @@ L.Map = L.Evented.extend({
 
 	getViewColor: function(viewid) {
 		if (this._docLayer._docType !== 'text') {
-			return L.LOUtil.getViewIdHexColor(viewid);
+			return L.LOUtil.getViewIdColor(viewid);
 		}
 
 		return this._viewInfo[viewid].color;
commit 6dff9dba683e479ea30bab6954fa7e7f8f75f1b3
Author: Miklos Vajna <vmiklos at collabora.co.uk>
Date:   Mon Nov 7 08:27:19 2016 +0100

    loolwsd: clean up unused using declarations
    
    Change-Id: Ib7fc0d2dbc10cbccacde327b29fe70f255d58a05
    (cherry picked from commit 121a47120386d03b250c3668ffeb93fff94b2388)

diff --git a/loolwsd/AdminModel.cpp b/loolwsd/AdminModel.cpp
index 24c9384..5142df0 100644
--- a/loolwsd/AdminModel.cpp
+++ b/loolwsd/AdminModel.cpp
@@ -25,8 +25,6 @@
 #include "Unit.hpp"
 #include "Util.hpp"
 
-using Poco::StringTokenizer;
-
 void Document::addView(const std::string& sessionId)
 {
     const auto ret = _views.emplace(sessionId, View(sessionId));
diff --git a/loolwsd/LOOLKit.cpp b/loolwsd/LOOLKit.cpp
index 50b6196..c97f247 100644
--- a/loolwsd/LOOLKit.cpp
+++ b/loolwsd/LOOLKit.cpp
@@ -74,13 +74,8 @@ using Poco::File;
 using Poco::JSON::Array;
 using Poco::JSON::Object;
 using Poco::JSON::Parser;
-using Poco::Net::HTTPClientSession;
-using Poco::Net::HTTPRequest;
-using Poco::Net::HTTPResponse;
 using Poco::Net::Socket;
 using Poco::Net::WebSocket;
-using Poco::Path;
-using Poco::Process;
 using Poco::Runnable;
 using Poco::StringTokenizer;
 using Poco::Thread;
@@ -88,6 +83,14 @@ using Poco::Timestamp;
 using Poco::URI;
 using Poco::Util::Application;
 
+#ifndef BUILDING_TESTS
+using Poco::Net::HTTPClientSession;
+using Poco::Net::HTTPRequest;
+using Poco::Net::HTTPResponse;
+using Poco::Path;
+using Poco::Process;
+#endif
+
 using namespace LOOLProtocol;
 
 // We only host a single document in our lifetime.
commit 4fd5402b0aa75bb64f36de2c7fe51916e36b159f
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 23:44:11 2016 -0500

    loolwsd: echo the unit-test command-line before running
    
    Change-Id: Ib061732bccd18112c5d3842c01e8d20d441816c0
    Reviewed-on: https://gerrit.libreoffice.org/30647
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit ea0e5e93447341a7324e344085a5874b027a12c7)

diff --git a/loolwsd/test/run_unit.sh.in b/loolwsd/test/run_unit.sh.in
index 652340f..06ee8a9 100755
--- a/loolwsd/test/run_unit.sh.in
+++ b/loolwsd/test/run_unit.sh.in
@@ -3,6 +3,11 @@
 # DO NOT EDIT - this file is generated from run_unit.sh.in.
 #
 
+echo
+echo "Running unit-test:"
+echo $0 $@
+echo
+
 # substituted variables in one place:
 DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
 abs_top_builddir="${DIR}/.."
commit 6ba4d5e395e71181afc07da152b727a9da998e0a
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 23:14:23 2016 -0500

    loolwsd: refactor DocumentBroker load and addSession
    
    Change-Id: I01db44561f79280f152bdf802efcbc064b22ab89
    Reviewed-on: https://gerrit.libreoffice.org/30646
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit 2507f7f89cbdc6787c6fa806b7b7fe7970dc68cd)

diff --git a/loolwsd/DocumentBroker.cpp b/loolwsd/DocumentBroker.cpp
index 50208ba..723b73b 100644
--- a/loolwsd/DocumentBroker.cpp
+++ b/loolwsd/DocumentBroker.cpp
@@ -165,8 +165,12 @@ DocumentBroker::~DocumentBroker()
     _childProcess.reset();
 }
 
-bool DocumentBroker::load(const std::string& sessionId, const std::string& jailId)
+bool DocumentBroker::load(std::shared_ptr<ClientSession>& session, const std::string& jailId)
 {
+    Util::assertIsLocked(_mutex);
+
+    const std::string sessionId = session->getId();
+
     LOG_INF("Loading [" << _docKey << "] for session [" << sessionId << "] and jail [" << jailId << "].");
 
     {
@@ -182,14 +186,6 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
         return false;
     }
 
-    auto it = _sessions.find(sessionId);
-    if (it == _sessions.end() || !it->second)
-    {
-        LOG_ERR("Session with sessionId [" << sessionId << "] not found while loading");
-        return false;
-    }
-
-    auto session = it->second;
     const Poco::URI& uriPublic = session->getPublicUri();
     LOG_DBG("Loading from URI: " << uriPublic.toString());
 
@@ -466,21 +462,13 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
     const auto id = session->getId();
     const std::string aMessage = "session " + id + " " + _docKey;
 
-    std::lock_guard<std::mutex> lock(_mutex);
-
-    auto ret = _sessions.emplace(id, session);
-    if (!ret.second)
-    {
-        LOG_WRN("DocumentBroker: Trying to add already existing session.");
-    }
+    std::unique_lock<std::mutex> lock(_mutex);
 
     try
     {
         // First load the document, since this can fail.
-        if (!load(id, std::to_string(_childProcess->getPid())))
+        if (!load(session, std::to_string(_childProcess->getPid())))
         {
-            _sessions.erase(id);
-
             const auto msg = "Failed to load document with URI [" + session->getPublicUri().toString() + "].";
             LOG_ERR(msg);
             throw std::runtime_error(msg);
@@ -489,7 +477,6 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
     catch (const StorageSpaceLowException&)
     {
         LOG_ERR("Out of storage while loading document with URI [" << session->getPublicUri().toString() << "].");
-        _sessions.erase(id);
 
         // We use the same message as is sent when some of lool's own locations are full,
         // even if in this case it might be a totally different location (file system, or
@@ -504,14 +491,23 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
     _lastEditableSession = false;
     _markToDestroy = false;
 
-    // Request a new session from the child kit.
-    _childProcess->sendTextFrame(aMessage);
-
     if (session->isReadOnly())
     {
         LOG_DBG("Adding a readonly session [" << id << "]");
     }
 
+    if (!_sessions.emplace(id, session).second)
+    {
+        LOG_WRN("DocumentBroker: Trying to add already existing session.");
+    }
+
+    const auto count = _sessions.size();
+
+    lock.unlock();
+
+    // Request a new session from the child kit.
+    _childProcess->sendTextFrame(aMessage);
+
     // Tell the admin console about this new doc
     Admin::instance().addDoc(_docKey, getPid(), getFilename(), id);
 
@@ -521,7 +517,7 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
     session->setPeer(prisonerSession);
     prisonerSession->setPeer(session);
 
-    return _sessions.size();
+    return count;
 }
 
 size_t DocumentBroker::removeSession(const std::string& id)
@@ -550,9 +546,10 @@ void DocumentBroker::alertAllUsersOfDocument(const std::string& cmd, const std::
 
     std::stringstream ss;
     ss << "error: cmd=" << cmd << " kind=" << kind;
+    const auto msg = ss.str();
     for (auto& it : _sessions)
     {
-        it.second->sendTextFrame(ss.str());
+        it.second->sendTextFrame(msg);
     }
 }
 
diff --git a/loolwsd/DocumentBroker.hpp b/loolwsd/DocumentBroker.hpp
index 60a7099..34195c9 100644
--- a/loolwsd/DocumentBroker.hpp
+++ b/loolwsd/DocumentBroker.hpp
@@ -198,7 +198,7 @@ public:
     ~DocumentBroker();
 
     /// Loads a document from the public URI into the jail.
-    bool load(const std::string& sessionId, const std::string& jailId);
+    bool load(std::shared_ptr<ClientSession>& session, const std::string& jailId);
     bool isLoaded() const { return _isLoaded; }
     void setLoaded() { _isLoaded = true; }
 
commit fe3e02382c4679f2977e2b9ba9cfa6c5bd8280e2
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 23:01:29 2016 -0500

    loolwsd: assert ChildProcess doesn't destroy DocumentBroker
    
    Change-Id: Iff20323f809f255557e05652ba08f7688b823fe1
    Reviewed-on: https://gerrit.libreoffice.org/30645
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit f3ffd5986039058a1dda24cb0ce3d8ca3fd331a2)

diff --git a/loolwsd/DocumentBroker.cpp b/loolwsd/DocumentBroker.cpp
index 7e250e4..50208ba 100644
--- a/loolwsd/DocumentBroker.cpp
+++ b/loolwsd/DocumentBroker.cpp
@@ -50,6 +50,9 @@ void ChildProcess::socketProcessor()
             auto docBroker = this->_docBroker.lock();
             if (docBroker)
             {
+                // We should never destroy the broker, since
+                // it owns us and will wait on this thread.
+                assert(docBroker.use_count() > 1);
                 return docBroker->handleInput(payload);
             }
 
commit a21bafd3e922088f1a8c87f3e129b11d13f4718c
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 22:29:19 2016 -0500

    loolwsd: name the child socket thread
    
    Change-Id: I079d821522b016cbd70a958b6a3e908a32b61f37
    Reviewed-on: https://gerrit.libreoffice.org/30644
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit f6698918925b3a8a934329fabbdc8bfad003cf87)

diff --git a/loolwsd/DocumentBroker.cpp b/loolwsd/DocumentBroker.cpp
index f18b049..7e250e4 100644
--- a/loolwsd/DocumentBroker.cpp
+++ b/loolwsd/DocumentBroker.cpp
@@ -34,12 +34,13 @@ using Poco::StringTokenizer;
 
 void ChildProcess::socketProcessor()
 {
+    Util::setThreadName("child_ws_" + std::to_string(_pid));
+
     IoUtil::SocketProcessor(_ws,
         [this](const std::vector<char>& payload)
         {
             const auto message = LOOLProtocol::getAbbreviatedMessage(payload);
-            LOG_TRC("Recv from child " << this->_pid <<
-                    ": [" << message << "].");
+            LOG_TRC("Recv from child [" << message << "].");
 
             if (UnitWSD::get().filterChildMessage(payload))
             {
commit 93e3274e68e73e30ce31992e2a486c5bf699d158
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 21:26:37 2016 -0500

    loolwsd: correct wsd initialization and preconditions
    
    For unit-tests at least listening to the public port before
    having forked forkit, let alone having a single child process
    ready, means we could starve and fail tests randomly.
    
    Here we first correct the order of initialization, such that
    the public port listening happens last. Second, we wait until
    we have at least one child successfully connected and ready.
    
    Change-Id: I7a31ad1ca4b30746f3cbf9c6b315670207cb7716
    Reviewed-on: https://gerrit.libreoffice.org/30643
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit a1d846b4311c0a36dda3301dcb1ce423cd0ec23e)

diff --git a/loolwsd/LOOLWSD.cpp b/loolwsd/LOOLWSD.cpp
index 30dc2b3..425b20f 100644
--- a/loolwsd/LOOLWSD.cpp
+++ b/loolwsd/LOOLWSD.cpp
@@ -294,9 +294,13 @@ static void preForkChildren()
 
     int numPreSpawn = LOOLWSD::NumPreSpawnedChildren;
     UnitWSD::get().preSpawnCount(numPreSpawn);
-    --numPreSpawn; // ForKit always spawns one child at startup.
 
+    --numPreSpawn; // ForKit always spawns one child at startup.
     forkChildren(numPreSpawn);
+
+    // Wait until we have at least one child.
+    const auto timeout = std::chrono::milliseconds(CHILD_TIMEOUT_MS);
+    NewChildrenCV.wait_for(lock, timeout, []() { return !NewChildren.empty(); });
 }
 
 /// Proatively spawn children processes
@@ -829,9 +833,8 @@ private:
         // Validate the broker.
         if (!docBroker || !docBroker->isAlive())
         {
-            // Cleanup later.
             LOG_ERR("DocBroker is invalid or premature termination of child "
-                       "process. Service Unavailable.");
+                    "process. Service Unavailable.");
             DocBrokers.erase(docKey);
 
             throw WebSocketErrorMessageException(SERVICE_UNAVAILABLE_INTERNAL_ERROR);
@@ -1905,21 +1908,9 @@ int LOOLWSD::main(const std::vector<std::string>& /*args*/)
     auto params2 = new HTTPServerParams();
     params2->setMaxThreads(MAX_SESSIONS);
 
-    // Start a server listening on the port for clients
-
-    std::unique_ptr<ServerSocket> psvs(
-        UnitWSD::isUnitTesting() ?
-            findFreeServerPort(ClientPortNumber) :
-            getServerSocket(ClientPortNumber, true));
-    if (!psvs)
-        return Application::EXIT_SOFTWARE;
-
     ThreadPool threadPool(NumPreSpawnedChildren * 6, MAX_SESSIONS * 2);
-    HTTPServer srv(new ClientRequestHandlerFactory(), threadPool, *psvs, params1);
-    LOG_INF("Starting master server listening on " << ClientPortNumber);
-    srv.start();
 
-    // And one on the port for child processes
+    // Start internal server for child processes.
     SocketAddress addr2("127.0.0.1", MasterPortNumber);
     std::unique_ptr<ServerSocket> psvs2(
         UnitWSD::isUnitTesting() ?
@@ -1927,11 +1918,12 @@ int LOOLWSD::main(const std::vector<std::string>& /*args*/)
             getMasterSocket(MasterPortNumber));
     if (!psvs2)
         return Application::EXIT_SOFTWARE;
+
     HTTPServer srv2(new PrisonerRequestHandlerFactory(), threadPool, *psvs2, params2);
     LOG_INF("Starting prisoner server listening on " << MasterPortNumber);
     srv2.start();
 
-    // Fire the ForKit process; we are ready.
+    // Fire the ForKit process; we are ready to get child connections.
     const Process::PID forKitPid = createForKit();
     if (forKitPid < 0)
     {
@@ -1945,12 +1937,23 @@ int LOOLWSD::main(const std::vector<std::string>& /*args*/)
     // Spawn some children, if necessary.
     preForkChildren();
 
-    time_t last30SecCheck = time(NULL);
+    // Now we can serve clients; Start listening on the public port.
+    std::unique_ptr<ServerSocket> psvs(
+        UnitWSD::isUnitTesting() ?
+            findFreeServerPort(ClientPortNumber) :
+            getServerSocket(ClientPortNumber, true));
+    if (!psvs)
+        return Application::EXIT_SOFTWARE;
+
+    HTTPServer srv(new ClientRequestHandlerFactory(), threadPool, *psvs, params1);
+    LOG_INF("Starting master server listening on " << ClientPortNumber);
+    srv.start();
 
 #if ENABLE_DEBUG
-    time_t startTimeSpan = last30SecCheck;
+    time_t startTimeSpan = time(nullptr);
 #endif
 
+    time_t last30SecCheck = time(nullptr);
     int status = 0;
     while (!TerminationFlag)
     {
@@ -2036,6 +2039,7 @@ int LOOLWSD::main(const std::vector<std::string>& /*args*/)
             // Make sure we have sufficient reserves.
             prespawnChildren();
         }
+
 #if ENABLE_DEBUG
         if (careerSpanSeconds > 0 && time(nullptr) > startTimeSpan + careerSpanSeconds)
         {
@@ -2053,7 +2057,7 @@ int LOOLWSD::main(const std::vector<std::string>& /*args*/)
     threadPool.joinAll();
 
     // Terminate child processes
-    LOG_INF("Requesting child process " << forKitPid << " to terminate");
+    LOG_INF("Requesting child process " << forKitPid << " to terminate.");
     Util::requestTermination(forKitPid);
     for (auto& child : NewChildren)
     {
commit 6849bedb14ee43356a072bfe9dbc32625db64b09
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 21:16:54 2016 -0500

    loolwsd: extend the lifetime of lokit to avoid destroying
    
    Lokit's destroy is prone to throw (at least in dbgutil).
    
    This exception brings the binary down with a core-dump.
    
    To avoid this, we extend the lifetime of lokit to the end
    of the process, where we invoke std::_Exit to promptly
    kill the process and exit.
    
    For reference, the exception is thrown as follows:
     #0  0x00007f0ba5a43bcd in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
     #1  0x00007f0b76303248 in (anonymous namespace)::ModuleManager::identify (this=0x7f0b5328e6d0, xModule=empty uno::Reference) at /home/ash/prjx/cp51/framework/source/services/modulemanager.cxx:198
     #2  0x00007f0b762606dc in (anonymous namespace)::JobExecutor::notifyEvent (this=0x7f0b77176b30, aEvent=...) at /home/ash/prjx/cp51/framework/source/jobs/jobexecutor.cxx:274
     #3  0x00007f0ba13ea455 in (anonymous namespace)::SfxGlobalEvents_Impl::implts_notifyJobExecution (this=0x7f0b77176a30, aEvent=...) at /home/ash/prjx/cp51/sfx2/source/notify/globalevents.cxx:397
     #4  0x00007f0ba13e9346 in (anonymous namespace)::SfxGlobalEvents_Impl::documentEventOccured (this=0x7f0b77176a30, _Event=...) at /home/ash/prjx/cp51/sfx2/source/notify/globalevents.cxx:241
     #5  0x00007f0ba0fe5717 in SfxTerminateListener_Impl::notifyTermination (this=0x7f0b772462c8, aEvent=...) at /home/ash/prjx/cp51/sfx2/source/appl/appinit.cxx:125
     #6  0x00007f0b762ebc39 in framework::Desktop::terminate (this=0x7f0b7721d530) at /home/ash/prjx/cp51/framework/source/services/desktop.cxx:330
     #7  0x00007f0ba47940ce in lo_destroy (pThis=0x154de60) at /home/ash/prjx/cp51/desktop/source/lib/init.cxx:2926
     #8  0x0000000000429681 in lok::Office::~Office (this=<optimized out>, __in_chrg=<optimized out>) at LibreOfficeKit.hpp:516
     #9  __gnu_cxx::new_allocator<lok::Office>::destroy<lok::Office> (this=<optimized out>, __p=<optimized out>) at /usr/include/c++/5/ext/new_allocator.h:124
     #10 std::allocator_traits<std::allocator<lok::Office> >::_S_destroy<lok::Office> (__p=<optimized out>, __a=...) at /usr/include/c++/5/bits/alloc_traits.h:285
     #11 std::allocator_traits<std::allocator<lok::Office> >::destroy<lok::Office> (__a=..., __p=<optimized out>) at /usr/include/c++/5/bits/alloc_traits.h:414
     #12 std::_Sp_counted_ptr_inplace<lok::Office, std::allocator<lok::Office>, (__gnu_cxx::_Lock_policy)2>::_M_dispose (this=0xb04f40) at /usr/include/c++/5/bits/shared_ptr_base.h:531
     #13 0x000000000042dfb6 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release (this=0xb04f40) at /usr/include/c++/5/bits/shared_ptr_base.h:150
     #14 0x0000000000425797 in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count (this=0x7ffce7430468, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr_base.h:659
     #15 std::__shared_ptr<lok::Office, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr (this=0x7ffce7430460, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr_base.h:925
     #16 std::shared_ptr<lok::Office>::~shared_ptr (this=0x7ffce7430460, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr.h:93
     #17 lokit_main (childRoot="/home/ash/prj/lo/online/loolwsd/test/../jails/", sysTemplate="/home/ash/prj/lo/online/loolwsd/test/../systemplate", loTemplate="/home/ash/prj/lo/instdir", loSubPath="lo", noCapabilities=<optimized out>, queryVersion=queryVersion at entry=true, displayVersion=false) at LOOLKit.cpp:1441
     #18 0x000000000041df41 in createLibreOfficeKit (childRoot="/home/ash/prj/lo/online/loolwsd/test/../jails/", sysTemplate="/home/ash/prj/lo/online/loolwsd/test/../systemplate", loTemplate="/home/ash/prj/lo/instdir", loSubPath="lo", queryVersion=queryVersion at entry=true) at LOOLForKit.cpp:228
     #19 0x000000000041aea4 in main (argc=7, argv=0x7ffce7431ec8) at LOOLForKit.cpp:389
    
    194         {
    195             throw css::lang::IllegalArgumentException(
    196                     OUString("Given module is not a frame nor a window, controller or model."),
    197                     static_cast< ::cppu::OWeakObject* >(this),
    198                     1);
    199         }
    
    Change-Id: Idaef5e0a28021a73f4c03ee3bee80968d9c57bd5
    Reviewed-on: https://gerrit.libreoffice.org/30642
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit 86fb4dc03bcefe198688cee00cd375112594dad7)

diff --git a/loolwsd/LOOLKit.cpp b/loolwsd/LOOLKit.cpp
index a89ba53..50b6196 100644
--- a/loolwsd/LOOLKit.cpp
+++ b/loolwsd/LOOLKit.cpp
@@ -1333,6 +1333,10 @@ void lokit_main(const std::string& childRoot,
     std::string userdir_url;
     std::string instdir_path;
 
+    // lokit's destroy typically throws from
+    // framework/source/services/modulemanager.cxx:198
+    // So we insure it lives until std::_Exit is called.
+    std::shared_ptr<lok::Office> loKit;
     Path jailPath;
     bool bRunInsideJail = !noCapabilities;
     try
@@ -1438,7 +1442,6 @@ void lokit_main(const std::string& childRoot,
             instdir_path = "/" + loTemplate + "/program";
         }
 
-        std::shared_ptr<lok::Office> loKit;
         {
             const char *instdir = instdir_path.c_str();
             const char *userdir = userdir_url.c_str();
@@ -1490,7 +1493,9 @@ void lokit_main(const std::string& childRoot,
                     std::string message(data.data(), data.size());
 
                     if (UnitKit::get().filterKitMessage(ws, message))
+                    {
                         return true;
+                    }
 
                     LOG_DBG(socketName << ": recv [" << LOOLProtocol::getAbbreviatedMessage(message) << "].");
                     StringTokenizer tokens(message, " ", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
diff --git a/loolwsd/LibreOfficeKit.hpp b/loolwsd/LibreOfficeKit.hpp
index 15108ec..cab4cbe 100644
--- a/loolwsd/LibreOfficeKit.hpp
+++ b/loolwsd/LibreOfficeKit.hpp
@@ -512,7 +512,14 @@ public:
     {
         std::unique_lock<std::mutex> lock(_mutex);
         Log::trace("lok::~Office dtor.");
-        _pOffice->pClass->destroy(_pOffice);
+        try
+        {
+            _pOffice->pClass->destroy(_pOffice);
+        }
+        catch (const std::exception& ex)
+        {
+            LOG_ERR("Exception while destroying LibreOfficeKit instance: " << ex.what());
+        }
     }
 
     /// This lock must be held while calling
commit f7ea09ce8d36177b1d31b60a89b262cd37e00a6b
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 21:16:11 2016 -0500

    loolwsd: new 'exit' command to request child process termination
    
    Change-Id: Id3f9bc67096b422630e04f59ed4ccbca012ddd4a
    Reviewed-on: https://gerrit.libreoffice.org/30641
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit 8cd8ca27a642c3049476a575948f63e34ebb8df8)

diff --git a/loolwsd/DocumentBroker.hpp b/loolwsd/DocumentBroker.hpp
index fdb7fac..60a7099 100644
--- a/loolwsd/DocumentBroker.hpp
+++ b/loolwsd/DocumentBroker.hpp
@@ -69,6 +69,18 @@ public:
     {
         LOG_DBG("Stopping ChildProcess [" << _pid << "]");
         _stop = true;
+
+        try
+        {
+            if (_pid != -1 && _ws)
+            {
+                sendTextFrame("exit");
+            }
+        }
+        catch (const std::exception&)
+        {
+            LOG_ERR("Failed to send 'exit' command to child [" << _pid << "].");
+        }
     }
 
     void close(const bool rude)
@@ -84,16 +96,19 @@ public:
             }
 
             _ws.reset();
-            if (_pid != -1)
+            if (_pid != -1 && kill(_pid, 0) != 0)
             {
-                LOG_INF("Closing child [" << _pid << "].");
-                if (rude && kill(_pid, SIGINT) != 0 && kill(_pid, 0) != 0)
+                if (rude)
                 {
-                    Log::syserror("Cannot terminate lokit [" + std::to_string(_pid) + "]. Abandoning.");
+                    LOG_INF("Killing child [" << _pid << "].");
+                    if (kill(_pid, SIGINT) != 0 && kill(_pid, 0) != 0)
+                    {
+                        Log::syserror("Cannot terminate lokit [" + std::to_string(_pid) + "]. Abandoning.");
+                    }
                 }
-
-                _pid = -1;
             }
+
+            _pid = -1;
         }
         catch (const std::exception& ex)
         {
@@ -108,9 +123,12 @@ public:
     {
         try
         {
-            LOG_TRC("DocBroker to Child: " << data);
-            _ws->sendFrame(data.data(), data.size());
-            return true;
+            if (_ws)
+            {
+                LOG_TRC("DocBroker to Child: " << data);
+                _ws->sendFrame(data.data(), data.size());
+                return true;
+            }
         }
         catch (const std::exception& exc)
         {
@@ -119,6 +137,7 @@ public:
             throw;
         }
 
+        LOG_WRN("No socket between DocBroker and child to send [" << data << "]");
         return false;
     }
 
diff --git a/loolwsd/LOOLKit.cpp b/loolwsd/LOOLKit.cpp
index 2fc199d..a89ba53 100644
--- a/loolwsd/LOOLKit.cpp
+++ b/loolwsd/LOOLKit.cpp
@@ -1521,6 +1521,11 @@ void lokit_main(const std::string& childRoot,
                             LOG_DBG("CreateSession failed.");
                         }
                     }
+                    else if (tokens[0] == "exit")
+                    {
+                        LOG_TRC("Setting TerminationFlag due to 'exit' command from parent.");
+                        TerminationFlag = true;
+                    }
                     else if (tokens[0] == "tile" || tokens[0] == "tilecombine" || tokens[0] == "canceltiles" ||
                              LOOLProtocol::getFirstToken(tokens[0], '-') == "child")
                     {
diff --git a/loolwsd/protocol.txt b/loolwsd/protocol.txt
index 560208f..f6035b9 100644
--- a/loolwsd/protocol.txt
+++ b/loolwsd/protocol.txt
@@ -395,6 +395,10 @@ disconnect
     Signals to the child that the client for the respective connection
     has disconnected.
 
+exit
+
+    Signals to the child that the process must end and exit.
+
 Admin console
 ===============
 
commit 5c45f2b79367eaa663b3c5ad8eea9e6aaff7918c
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 22:11:59 2016 -0500

    loolwsd: correct document loading and error handling
    
    Change-Id: I7529c8584356f5eea3c91b5d5ffdd6a956710241
    Reviewed-on: https://gerrit.libreoffice.org/30640
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit f1f1ff7057871e27be98b3fe6a92ad4d8a72608d)

diff --git a/loolwsd/DocumentBroker.cpp b/loolwsd/DocumentBroker.cpp
index 1613aec..f18b049 100644
--- a/loolwsd/DocumentBroker.cpp
+++ b/loolwsd/DocumentBroker.cpp
@@ -462,33 +462,21 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
     const auto id = session->getId();
     const std::string aMessage = "session " + id + " " + _docKey;
 
-    try
-    {
-        std::lock_guard<std::mutex> lock(_mutex);
-
-        // Request a new session from the child kit.
-        _childProcess->sendTextFrame(aMessage);
+    std::lock_guard<std::mutex> lock(_mutex);
 
-        auto ret = _sessions.emplace(id, session);
-        if (!ret.second)
-        {
-            LOG_WRN("DocumentBroker: Trying to add already existing session.");
-        }
+    auto ret = _sessions.emplace(id, session);
+    if (!ret.second)
+    {
+        LOG_WRN("DocumentBroker: Trying to add already existing session.");
+    }
 
-        if (session->isReadOnly())
+    try
+    {
+        // First load the document, since this can fail.
+        if (!load(id, std::to_string(_childProcess->getPid())))
         {
-            LOG_DBG("Adding a readonly session [" << id << "]");
-        }
+            _sessions.erase(id);
 
-        // Below values are recalculated when startDestroy() is called (before destroying the
-        // document). It is safe to reset their values to their defaults whenever a new session is added.
-        _lastEditableSession = false;
-        _markToDestroy = false;
-
-        bool loaded;
-        loaded = load(id, std::to_string(_childProcess->getPid()));
-        if (!loaded)
-        {
             const auto msg = "Failed to load document with URI [" + session->getPublicUri().toString() + "].";
             LOG_ERR(msg);
             throw std::runtime_error(msg);
@@ -496,6 +484,9 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
     }
     catch (const StorageSpaceLowException&)
     {
+        LOG_ERR("Out of storage while loading document with URI [" << session->getPublicUri().toString() << "].");
+        _sessions.erase(id);
+
         // We use the same message as is sent when some of lool's own locations are full,
         // even if in this case it might be a totally different location (file system, or
         // some other type of storage somewhere). This message is not sent to all clients,
@@ -504,6 +495,19 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
         throw;
     }
 
+    // Below values are recalculated when startDestroy() is called (before destroying the
+    // document). It is safe to reset their values to their defaults whenever a new session is added.
+    _lastEditableSession = false;
+    _markToDestroy = false;
+
+    // Request a new session from the child kit.
+    _childProcess->sendTextFrame(aMessage);
+
+    if (session->isReadOnly())
+    {
+        LOG_DBG("Adding a readonly session [" << id << "]");
+    }
+
     // Tell the admin console about this new doc
     Admin::instance().addDoc(_docKey, getPid(), getFilename(), id);
 
@@ -538,7 +542,7 @@ size_t DocumentBroker::removeSession(const std::string& id)
 
 void DocumentBroker::alertAllUsersOfDocument(const std::string& cmd, const std::string& kind)
 {
-    std::lock_guard<std::mutex> lock(_mutex);
+    Util::assertIsLocked(_mutex);
 
     std::stringstream ss;
     ss << "error: cmd=" << cmd << " kind=" << kind;
commit 8ef7f27aae90e331a838182d62fce1f930837d95
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 22:11:35 2016 -0500

    loolwsd: better use named variable than it->second
    
    Change-Id: Ia336b9001911dfd2cf1c19c1536f52bed7684a2a
    Reviewed-on: https://gerrit.libreoffice.org/30639
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit 71f2f4921d4edd344d7742ee3b737faf4d3f46e7)

diff --git a/loolwsd/DocumentBroker.cpp b/loolwsd/DocumentBroker.cpp
index cbc710c..1613aec 100644
--- a/loolwsd/DocumentBroker.cpp
+++ b/loolwsd/DocumentBroker.cpp
@@ -38,7 +38,7 @@ void ChildProcess::socketProcessor()
         [this](const std::vector<char>& payload)
         {
             const auto message = LOOLProtocol::getAbbreviatedMessage(payload);
-            LOG_WRN("Recv from child " << this->_pid <<
+            LOG_TRC("Recv from child " << this->_pid <<
                     ": [" << message << "].");
 
             if (UnitWSD::get().filterChildMessage(payload))
@@ -179,13 +179,14 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
     }
 
     auto it = _sessions.find(sessionId);
-    if (it == _sessions.end())
+    if (it == _sessions.end() || !it->second)
     {
         LOG_ERR("Session with sessionId [" << sessionId << "] not found while loading");
         return false;
     }
 
-    const Poco::URI& uriPublic = it->second->getPublicUri();
+    auto session = it->second;
+    const Poco::URI& uriPublic = session->getPublicUri();
     LOG_DBG("Loading from URI: " << uriPublic.toString());
 
     _jailId = jailId;
@@ -232,12 +233,12 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
         if (!wopifileinfo._userCanWrite)
         {
             LOG_DBG("Setting the session as readonly");
-            it->second->setReadOnly();
+            session->setReadOnly();
         }
 
         if (!wopifileinfo._postMessageOrigin.empty())
         {
-            it->second->sendTextFrame("wopi: postmessageorigin " + wopifileinfo._postMessageOrigin);
+            session->sendTextFrame("wopi: postmessageorigin " + wopifileinfo._postMessageOrigin);
         }
 
         getInfoCallDuration = wopifileinfo._callDuration;
@@ -250,8 +251,8 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
     }
 
     LOG_DBG("Setting username [" << username << "] and userId [" << userid << "] for session [" << sessionId << "]");
-    it->second->setUserId(userid);
-    it->second->setUserName(username);
+    session->setUserId(userid);
+    session->setUserName(username);
 
     // Get basic file information from the storage
     const auto fileInfo = _storage->getFileInfo();
@@ -283,7 +284,7 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
         callDuration += getInfoCallDuration;
         const std::string msg = "stats: wopiloadduration " + std::to_string(callDuration.count());
         LOG_TRC("Sending to Client [" << msg << "].");
-        it->second->sendTextFrame(msg);
+        session->sendTextFrame(msg);
     }
 
     return true;
commit 9c5d07f7044afa1c00756299ce0526a4b57a808d
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 21:55:37 2016 -0500

    loolwsd: inline and simplify connectPeers
    
    Change-Id: I64fbeefa59573eb9e467dc18ecbf75ebd72b3be4
    Reviewed-on: https://gerrit.libreoffice.org/30638
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit 11a0d016cabf13b990f975af8d06b44ca15cd8bf)

diff --git a/loolwsd/DocumentBroker.cpp b/loolwsd/DocumentBroker.cpp
index 1462d3c..cbc710c 100644
--- a/loolwsd/DocumentBroker.cpp
+++ b/loolwsd/DocumentBroker.cpp
@@ -509,29 +509,12 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
     auto prisonerSession = std::make_shared<PrisonerSession>(id, shared_from_this());
 
     // Connect the prison session to the client.
-    if (!connectPeers(prisonerSession))
-    {
-        LOG_WRN("Failed to connect " << session->getName() << " to its peer.");
-    }
+    session->setPeer(prisonerSession);
+    prisonerSession->setPeer(session);
 
     return _sessions.size();
 }
 
-bool DocumentBroker::connectPeers(std::shared_ptr<PrisonerSession>& session)
-{
-    const auto id = session->getId();
-
-    auto it = _sessions.find(id);
-    if (it != _sessions.end())
-    {
-        it->second->setPeer(session);
-        session->setPeer(it->second);
-        return true;
-    }
-
-    return false;
-}
-
 size_t DocumentBroker::removeSession(const std::string& id)
 {
     Util::assertIsLocked(_mutex);
diff --git a/loolwsd/DocumentBroker.hpp b/loolwsd/DocumentBroker.hpp
index 73b1697..fdb7fac 100644
--- a/loolwsd/DocumentBroker.hpp
+++ b/loolwsd/DocumentBroker.hpp
@@ -221,8 +221,6 @@ public:
 
     /// Add a new session. Returns the new number of sessions.
     size_t addSession(std::shared_ptr<ClientSession>& session);
-    /// Connect a prison session to its client peer.
-    bool connectPeers(std::shared_ptr<PrisonerSession>& session);
     /// Removes a session by ID. Returns the new number of sessions.
     size_t removeSession(const std::string& id);
 
commit d4231f910b2e1800c54a0eb2871a957372abc653
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 13:54:00 2016 -0500

    loolwsd: cleanup document and storage loading in WSD
    
    Change-Id: I4d6bdda131efb6270fbd5864034ac619cf86ef3d
    Reviewed-on: https://gerrit.libreoffice.org/30637
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit 4e13f1b37c94a4e39197ec45d1db30acdae904fa)

diff --git a/loolwsd/DocumentBroker.cpp b/loolwsd/DocumentBroker.cpp
index cf66a4a..1462d3c 100644
--- a/loolwsd/DocumentBroker.cpp
+++ b/loolwsd/DocumentBroker.cpp
@@ -163,6 +163,8 @@ DocumentBroker::~DocumentBroker()
 
 bool DocumentBroker::load(const std::string& sessionId, const std::string& jailId)
 {
+    LOG_INF("Loading [" << _docKey << "] for session [" << sessionId << "] and jail [" << jailId << "].");
+
     {
         bool result;
         if (UnitWSD::get().filterLoad(sessionId, jailId, result))
@@ -172,6 +174,7 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
     if (_markToDestroy)
     {
         // Tearing down.
+        LOG_WRN("Will not load document marked to destroy. DocKey: [" << _docKey << "].");
         return false;
     }
 
@@ -193,11 +196,12 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
     // user/doc/jailId
     const auto jailPath = Poco::Path(JAILED_DOCUMENT_ROOT, jailId);
     std::string jailRoot = getJailRoot();
-
-    LOG_INF("jailPath: " << jailPath.toString() << ", jailRoot: " << jailRoot);
-
     if (LOOLWSD::NoCapsForKit)
+    {
         jailRoot = jailPath.toString() + "/" + getJailRoot();
+    }
+
+    LOG_INF("jailPath: " << jailPath.toString() << ", jailRoot: " << jailRoot);
 
     if (_storage == nullptr)
     {
@@ -206,80 +210,83 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
         // different query params like access token etc.)
         LOG_DBG("Creating new storage instance for URI [" << uriPublic.toString() << "].");
         _storage = StorageBase::create(uriPublic, jailRoot, jailPath.toString());
-    }
-
-    if (_storage)
-    {
-        // Call the storage specific file info functions
-        std::string userid, username;
-        std::chrono::duration<double> getInfoCallDuration;
-        if (dynamic_cast<WopiStorage*>(_storage.get()) != nullptr)
+        if (_storage == nullptr)
         {
-            const WopiStorage::WOPIFileInfo wopifileinfo = static_cast<WopiStorage*>(_storage.get())->getWOPIFileInfo(uriPublic);
-            userid = wopifileinfo._userid;
-            username = wopifileinfo._username;
+            // We should get an exception, not null.
+            LOG_ERR("Failed to create Storage instance for [" << _docKey << "] in " << jailPath.toString());
+            return false;
+        }
+    }
 
-            if (!wopifileinfo._userCanWrite)
-            {
-                LOG_DBG("Setting the session as readonly");
-                it->second->setReadOnly();
-            }
+    assert(_storage != nullptr);
 
-            if (!wopifileinfo._postMessageOrigin.empty())
-            {
-                it->second->sendTextFrame("wopi: postmessageorigin " + wopifileinfo._postMessageOrigin);
-            }
+    // Call the storage specific file info functions
+    std::string userid, username;
+    std::chrono::duration<double> getInfoCallDuration;
+    if (dynamic_cast<WopiStorage*>(_storage.get()) != nullptr)
+    {
+        const WopiStorage::WOPIFileInfo wopifileinfo = static_cast<WopiStorage*>(_storage.get())->getWOPIFileInfo(uriPublic);
+        userid = wopifileinfo._userid;
+        username = wopifileinfo._username;
 
-            getInfoCallDuration = wopifileinfo._callDuration;
-        }
-        else if (dynamic_cast<LocalStorage*>(_storage.get()) != nullptr)
+        if (!wopifileinfo._userCanWrite)
         {
-            const LocalStorage::LocalFileInfo localfileinfo = static_cast<LocalStorage*>(_storage.get())->getLocalFileInfo(uriPublic);
-            userid = localfileinfo._userid;
-            username = localfileinfo._username;
+            LOG_DBG("Setting the session as readonly");
+            it->second->setReadOnly();
         }
 
-        LOG_DBG("Setting username [" << username << "] and userId [" << userid << "] for session [" << sessionId << "]");
-        it->second->setUserId(userid);
-        it->second->setUserName(username);
-
-        // Get basic file information from the storage
-        const auto fileInfo = _storage->getFileInfo();
-        if (!fileInfo.isValid())
+        if (!wopifileinfo._postMessageOrigin.empty())
         {
-            LOG_ERR("Invalid fileinfo for URI [" << uriPublic.toString() << "].");
-            return false;
+            it->second->sendTextFrame("wopi: postmessageorigin " + wopifileinfo._postMessageOrigin);
         }
 
-        // Lets load the document now
-        const bool loaded = _storage->isLoaded();
-        if (!loaded)
-        {
-            const auto localPath = _storage->loadStorageFileToLocal();
-            _uriJailed = Poco::URI(Poco::URI("file://"), localPath);
-            _filename = fileInfo._filename;
+        getInfoCallDuration = wopifileinfo._callDuration;
+    }
+    else if (dynamic_cast<LocalStorage*>(_storage.get()) != nullptr)
+    {
+        const LocalStorage::LocalFileInfo localfileinfo = static_cast<LocalStorage*>(_storage.get())->getLocalFileInfo(uriPublic);
+        userid = localfileinfo._userid;
+        username = localfileinfo._username;
+    }
 
-            // Use the local temp file's timestamp.
-            _lastFileModifiedTime = Poco::File(_storage->getLocalRootPath()).getLastModified();
-            _tileCache.reset(new TileCache(_uriPublic.toString(), _lastFileModifiedTime, _cacheRoot));
-        }
+    LOG_DBG("Setting username [" << username << "] and userId [" << userid << "] for session [" << sessionId << "]");
+    it->second->setUserId(userid);
+    it->second->setUserName(username);
 
-        // Since document has been loaded, send the stats if its WOPI
-        if (dynamic_cast<WopiStorage*>(_storage.get()) != nullptr)
-        {
-            // Get the time taken to load the file from storage
-            auto callDuration = static_cast<WopiStorage*>(_storage.get())->getWopiLoadDuration();
-            // Add the time taken to check file info
-            callDuration += getInfoCallDuration;
-            const std::string msg = "stats: wopiloadduration " + std::to_string(callDuration.count());
-            LOG_TRC("Sending to Client [" << msg << "].");
-            it->second->sendTextFrame(msg);
-        }
+    // Get basic file information from the storage
+    const auto fileInfo = _storage->getFileInfo();
+    if (!fileInfo.isValid())
+    {
+        LOG_ERR("Invalid fileinfo for URI [" << uriPublic.toString() << "].");
+        return false;
+    }
 
-        return true;
+    // Lets load the document now
+    const bool loaded = _storage->isLoaded();
+    if (!loaded)
+    {
+        const auto localPath = _storage->loadStorageFileToLocal();
+        _uriJailed = Poco::URI(Poco::URI("file://"), localPath);
+        _filename = fileInfo._filename;
+
+        // Use the local temp file's timestamp.
+        _lastFileModifiedTime = Poco::File(_storage->getLocalRootPath()).getLastModified();
+        _tileCache.reset(new TileCache(_uriPublic.toString(), _lastFileModifiedTime, _cacheRoot));
     }
 
-    return false;
+    // Since document has been loaded, send the stats if its WOPI
+    if (dynamic_cast<WopiStorage*>(_storage.get()) != nullptr)
+    {
+        // Get the time taken to load the file from storage
+        auto callDuration = static_cast<WopiStorage*>(_storage.get())->getWopiLoadDuration();
+        // Add the time taken to check file info
+        callDuration += getInfoCallDuration;
+        const std::string msg = "stats: wopiloadduration " + std::to_string(callDuration.count());
+        LOG_TRC("Sending to Client [" << msg << "].");
+        it->second->sendTextFrame(msg);
+    }
+
+    return true;
 }
 
 bool DocumentBroker::save(const std::string& sessionId, bool success, const std::string& result)
commit 5c886b668923278180d65a7100733b8ba4b9657c
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 13:35:03 2016 -0500

    loolwsd: LOOLKit logs updated
    
    Change-Id: I003d060ac2fd5673d57f7c175837ac3daf335f17
    Reviewed-on: https://gerrit.libreoffice.org/30636
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit a5f1597e0f0bb421a13252d55379ca6a73e5b0c4)

diff --git a/loolwsd/LOOLKit.cpp b/loolwsd/LOOLKit.cpp
index 75f2f87..2fc199d 100644
--- a/loolwsd/LOOLKit.cpp
+++ b/loolwsd/LOOLKit.cpp
@@ -158,7 +158,7 @@ namespace
                 }
                 if (!shouldCopyDir(relativeOldPath))
                 {
-                    Log::trace("skip redundant paths " + std::string(relativeOldPath));
+                    LOG_TRC("skip redundant paths " << relativeOldPath);
                     return FTW_SKIP_SUBTREE;
                 }
                 File(newPath).createDirectories();
@@ -173,13 +173,13 @@ namespace
             }
             break;
         case FTW_DNR:
-            Log::error("Cannot read directory '" + std::string(fpath) + "'");
+            LOG_ERR("Cannot read directory '" << fpath << "'");
             return 1;
         case FTW_NS:
-            Log::error("nftw: stat failed for '" + std::string(fpath) + "'");
+            LOG_ERR("nftw: stat failed for '" << fpath << "'");
             return 1;
         default:
-            Log::fatal("nftw: unexpected type: '" + std::to_string(typeflag));
+            LOG_FTL("nftw: unexpected type: '" << typeflag);
             assert(false);
             break;
         }
@@ -196,7 +196,7 @@ namespace
             sourceForLinkOrCopy.pop_back();
         destinationForLinkOrCopy = destination;
         if (nftw(source.c_str(), linkOrCopyFunction, 10, FTW_ACTIONRETVAL) == -1)
-            Log::error("linkOrCopy: nftw() failed for '" + source + "'");
+            LOG_ERR("linkOrCopy: nftw() failed for '" << source << "'");
     }
 
     void dropCapability(cap_value_t capability)
@@ -212,7 +212,7 @@ namespace
         }
 
         char *capText = cap_to_text(caps, nullptr);
-        Log::trace("Capabilities first: " + std::string(capText));
+        LOG_TRC("Capabilities first: " << capText);
         cap_free(capText);
 
         if (cap_set_flag(caps, CAP_EFFECTIVE, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1 ||
@@ -229,7 +229,7 @@ namespace
         }
 
         capText = cap_to_text(caps, nullptr);
-        Log::trace("Capabilities now: " + std::string(capText));
+        LOG_TRC("Capabilities now: " << capText);
         cap_free(capText);
 
         cap_free(caps);
@@ -246,7 +246,7 @@ namespace
             symlinkTarget += "../";
         symlinkTarget += loSubPath;
 
-        Log::debug("symlink(\"" + symlinkTarget + "\",\"" + symlinkSource.toString() + "\")");
+        LOG_DBG("symlink(\"" << symlinkTarget << "\",\"" << symlinkSource.toString() << "\")");
         if (symlink(symlinkTarget.c_str(), symlinkSource.toString().c_str()) == -1)
         {
             Log::syserror("symlink(\"" + symlinkTarget + "\",\"" + symlinkSource.toString() + "\") failed");
@@ -292,7 +292,7 @@ public:
         _mutex(),
         _isLoading(0)
     {
-        Log::info("Document ctor for url [" + _url + "] on child [" + _jailId + "].");
+        LOG_INF("Document ctor for url [" << _url << "] on child [" << _jailId << "].");
         assert(_loKit && _loKit->get());
 
         _callbackThread.start(*this);
@@ -301,7 +301,7 @@ public:
     ~Document()
     {
         LOG_INF("~Document dtor for url [" << _url << "] on child [" << _jailId <<
-                  "]. There are " << _sessions.size() << " views.");
+                "]. There are " << _sessions.size() << " views.");
 
         // Wait for the callback worker to finish.
         _stop = true;
@@ -389,7 +389,7 @@ public:
 
         if (numRunning == 0)
         {
-            Log::info("No more sessions, exiting bluntly");
+            LOG_INF("No more sessions, exiting bluntly");
             std::_Exit(Application::EXIT_OK);
         }
 
@@ -421,9 +421,9 @@ public:
     /// Set Document password for given URL
     void setDocumentPassword(int nPasswordType)
     {
-        Log::info() << "setDocumentPassword: passwordProtected=" << _isDocPasswordProtected
-                    << " passwordProvided=" << _haveDocPassword
-                    << " password='" << _docPassword <<  "'" << Log::end;
+        LOG_INF("setDocumentPassword: passwordProtected=" << _isDocPasswordProtected <<
+                " passwordProvided=" << _haveDocPassword <<
+                " password='" << _docPassword <<  "'");
 
         if (_isDocPasswordProtected && _haveDocPassword)
         {
@@ -439,12 +439,12 @@ public:
         else if (nPasswordType == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY)
             _docPasswordType = PasswordType::ToModify;
 
-        Log::info("Calling _loKit->setDocumentPassword");
+        LOG_INF("Calling _loKit->setDocumentPassword");
         if (_haveDocPassword)
             _loKit->setDocumentPassword(_jailedUrl.c_str(), _docPassword.c_str());
         else
             _loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr);
-        Log::info("setDocumentPassword returned");
+        LOG_INF("setDocumentPassword returned");
     }
 
     void renderTile(StringTokenizer& tokens, const std::shared_ptr<Poco::Net::WebSocket>& ws)
@@ -470,14 +470,14 @@ public:
 
         if (!_loKitDocument)
         {
-            Log::error("Tile rendering requested before loading document.");
+            LOG_ERR("Tile rendering requested before loading document.");
             return;
         }
 
         std::unique_lock<std::mutex> lock(_loKitDocument->getLock());
         if (_loKitDocument->getViewsCount() <= 0)
         {
-            Log::error("Tile rendering requested without views.");
+            LOG_ERR("Tile rendering requested without views.");
             return;
         }
 
@@ -488,16 +488,16 @@ public:
                                       tile.getTilePosX(), tile.getTilePosY(),
                                       tile.getTileWidth(), tile.getTileHeight());
         const auto elapsed = timestamp.elapsed();
-        Log::trace() << "paintTile at (" << tile.getPart() << ',' << tile.getTilePosX() << ',' << tile.getTilePosY()
-                     << ") " << "ver: " << tile.getVersion() << " rendered in " << (elapsed/1000.)
-                     << " ms (" << area / elapsed << " MP/s)." << Log::end;
+        LOG_TRC("paintTile at (" << tile.getPart() << ',' << tile.getTilePosX() << ',' << tile.getTilePosY() <<
+                ") " << "ver: " << tile.getVersion() << " rendered in " << (elapsed/1000.) <<
+                " ms (" << area / elapsed << " MP/s).");
         const auto mode = static_cast<LibreOfficeKitTileMode>(_loKitDocument->getTileMode());
 
         if (!png::encodeBufferToPNG(pixmap.data(), tile.getWidth(), tile.getHeight(), output, mode))
         {
             //FIXME: Return error.
             //sendTextFrame("error: cmd=tile kind=failure");
-            Log::error("Failed to encode tile into PNG.");
+            LOG_ERR("Failed to encode tile into PNG.");
             return;
         }
 
@@ -508,7 +508,7 @@ public:
             ws->sendFrame(nextmessage.data(), nextmessage.size());
         }
 
-        Log::trace("Sending render-tile response (" + std::to_string(length) + " bytes) for: " + response);
+        LOG_TRC("Sending render-tile response (" << length << " bytes) for: " << response);
         ws->sendFrame(output.data(), length, WebSocket::FRAME_BINARY);
     }
 
@@ -548,14 +548,14 @@ public:
 
         if (!_loKitDocument)
         {
-            Log::error("Tile rendering requested before loading document.");
+            LOG_ERR("Tile rendering requested before loading document.");
             return;
         }
 
         std::unique_lock<std::mutex> lock(_loKitDocument->getLock());
         if (_loKitDocument->getViewsCount() <= 0)
         {
-            Log::error("Tile rendering requested without views.");
+            LOG_ERR("Tile rendering requested without views.");
             return;
         }
 
@@ -566,9 +566,9 @@ public:
                                       renderArea.getLeft(), renderArea.getTop(),
                                       renderArea.getWidth(), renderArea.getHeight());
         const auto elapsed = timestamp.elapsed();
-        Log::debug() << "paintTile (combined) at (" << renderArea.getLeft() << ", " << renderArea.getTop() << "), ("
-                     << renderArea.getWidth() << ", " << renderArea.getHeight() << ") ver: " << tileCombined.getVersion()
-                     << " rendered in " << (elapsed/1000.) << " ms (" << area / elapsed << " MP/s)." << Log::end;
+        LOG_DBG("paintTile (combined) at (" << renderArea.getLeft() << ", " << renderArea.getTop() << "), (" <<
+                renderArea.getWidth() << ", " << renderArea.getHeight() << ") ver: " << tileCombined.getVersion() <<
+                " rendered in " << (elapsed/1000.) << " ms (" << area / elapsed << " MP/s).");
         const auto mode = static_cast<LibreOfficeKitTileMode>(_loKitDocument->getTileMode());
 
         std::vector<char> output;
@@ -588,12 +588,12 @@ public:
             {
                 //FIXME: Return error.
                 //sendTextFrame("error: cmd=tile kind=failure");
-                Log::error("Failed to encode tile into PNG.");
+                LOG_ERR("Failed to encode tile into PNG.");
                 return;
             }
 
             const auto imgSize = output.size() - oldSize;
-            Log::trace() << "Encoded tile #" << tileIndex << " in " << imgSize << " bytes." << Log::end;
+            LOG_TRC("Encoded tile #" << tileIndex << " in " << imgSize << " bytes.");
             tiles[tileIndex++].setImgSize(imgSize);
         }
 
@@ -602,7 +602,7 @@ public:
 #else
         const auto tileMsg = tileCombined.serialize("tilecombine:") + "\n";
 #endif
-        Log::trace("Sending back painted tiles for " + tileMsg);
+        LOG_TRC("Sending back painted tiles for " << tileMsg);
 
         std::vector<char> response;
         response.resize(tileMsg.size() + output.size());
@@ -625,7 +625,7 @@ public:
         {
             if (!_ws || _ws->poll(Poco::Timespan(0), Socket::SelectMode::SELECT_ERROR))
             {
-                Log::error("Child Doc: Bad socket while sending [" + getAbbreviatedMessage(message) + "].");
+                LOG_ERR("Child Doc: Bad socket while sending [" << getAbbreviatedMessage(message) << "].");
                 return false;
             }
 
@@ -642,9 +642,8 @@ public:
         }
         catch (const Exception& exc)
         {
-            Log::error() << "Document::sendTextFrame: "
-                         << "Exception: " << exc.displayText()
-                         << (exc.nested() ? "( " + exc.nested()->displayText() + ")" : "");
+            LOG_ERR("Document::sendTextFrame: Exception: " << exc.displayText() <<
+                    (exc.nested() ? "( " + exc.nested()->displayText() + ")" : ""));
         }
 
         return false;
@@ -658,9 +657,8 @@ public:
         }
 
         const std::string payload = pPayload ? pPayload : "(nil)";
-        Log::trace() << "Document::GlobalCallback "
-                     << LOKitHelper::kitCallbackTypeToString(nType)
-                     << " [" << payload << "]." << Log::end;
+        LOG_TRC("Document::GlobalCallback " << LOKitHelper::kitCallbackTypeToString(nType) <<
+                " [" << payload << "].");
         Document* self = reinterpret_cast<Document*>(pData);
         if (nType == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY ||
             nType == LOK_CALLBACK_DOCUMENT_PASSWORD)
@@ -686,9 +684,9 @@ public:
         assert(pDescr->Doc && "Null Document instance.");
 
         const std::string payload = pPayload ? pPayload : "(nil)";
-        Log::trace() << "Document::ViewCallback [" << pDescr->ViewId
-                     << "] [" << LOKitHelper::kitCallbackTypeToString(nType)
-                     << "] [" << payload << "]." << Log::end;
+        LOG_TRC("Document::ViewCallback [" << pDescr->ViewId <<
+                "] [" << LOKitHelper::kitCallbackTypeToString(nType) <<
+                "] [" << payload << "].");
 
         std::unique_lock<std::mutex> lock(pDescr->Doc->getMutex());
 
@@ -742,9 +740,8 @@ private:
         }
 
         const std::string payload = pPayload ? pPayload : "(nil)";
-        Log::trace() << "Document::DocumentCallback "
-                     << LOKitHelper::kitCallbackTypeToString(nType)
-                     << " [" << payload << "]." << Log::end;
+        LOG_TRC("Document::DocumentCallback " << LOKitHelper::kitCallbackTypeToString(nType) <<
+                " [" << payload << "].");
         Document* self = reinterpret_cast<Document*>(pData);
         self->broadcastCallbackToClients(nType, pPayload);
     }
@@ -887,7 +884,7 @@ private:
             int color = 0;
             if (viewInfoMap.find(viewId) == viewInfoMap.end())
             {
-                Log::error("No username found for viewId [" + std::to_string(viewId) + "].");
+                LOG_ERR("No username found for viewId [" << viewId << "].");
                 viewInfoObj->set("username", "Unknown");
             }
             else
@@ -955,9 +952,8 @@ private:
         }
         catch(const Exception& exc)
         {
-            Log::error() << "Poco Exception: " << exc.displayText()
-                         << (exc.nested() ? " (" + exc.nested()->displayText() + ")" : "")
-                         << Log::end;
+            LOG_ERR("Poco Exception: " << exc.displayText() <<
+                    (exc.nested() ? " (" + exc.nested()->displayText() + ")" : ""));
         }
 
         return viewColors;
@@ -973,7 +969,7 @@ private:
         const auto it = _sessions.find(sessionId);
         if (it == _sessions.end() || !it->second)
         {
-            Log::error("Cannot find session [" + sessionId + "].");
+            LOG_ERR("Cannot find session [" << sessionId << "].");
             return nullptr;
         }
 
@@ -984,7 +980,7 @@ private:
         if (!_loKitDocument)
         {
             // This is the first time we are loading the document
-            Log::info("Loading new document from URI: [" + uri + "] for session [" + sessionId + "].");
+            LOG_INF("Loading new document from URI: [" << uri << "] for session [" << sessionId << "].");
 
             auto lock(_loKit->getLock());
 
@@ -1003,23 +999,23 @@ private:
             _jailedUrl = uri;
             _isDocPasswordProtected = false;
 
-            Log::debug("Calling lokit::documentLoad.");
+            LOG_DBG("Calling lokit::documentLoad.");
             _loKitDocument = _loKit->documentLoad(uri.c_str());
-            Log::debug("Returned lokit::documentLoad.");
+            LOG_DBG("Returned lokit::documentLoad.");
             auto l(_loKitDocument->getLock());
             lockLokDoc.swap(l);
 
             if (!_loKitDocument || !_loKitDocument->get())
             {
-                Log::error("Failed to load: " + uri + ", error: " + _loKit->getError());
+                LOG_ERR("Failed to load: " << uri << ", error: " << _loKit->getError());
 
                 // Checking if wrong password or no password was reason for failure.
                 if (_isDocPasswordProtected)
                 {
-                    Log::info("Document [" + uri + "] is password protected.");
+                    LOG_INF("Document [" << uri << "] is password protected.");
                     if (!_haveDocPassword)
                     {
-                        Log::info("No password provided for password-protected document [" + uri + "].");
+                        LOG_INF("No password provided for password-protected document [" << uri << "].");
                         std::string passwordFrame = "passwordrequired:";
                         if (_docPasswordType == PasswordType::ToView)
                             passwordFrame += "to-view";
@@ -1029,7 +1025,7 @@ private:
                     }
                     else
                     {
-                        Log::info("Wrong password for password-protected document [" + uri + "].");
+                        LOG_INF("Wrong password for password-protected document [" << uri << "].");
                         session->sendTextFrame("error: cmd=load kind=wrongpassword");
                     }
                 }
@@ -1066,9 +1062,9 @@ private:
                 }
             }
 
-            Log::info("Loading view to document from URI: [" + uri + "] for session [" + sessionId + "].");
+            LOG_INF("Loading view to document from URI: [" << uri << "] for session [" << sessionId << "].");
             _loKitDocument->createView();
-            Log::trace("View created.");
+            LOG_TRC("View created.");
         }
 
         Util::assertIsLocked(lockLokDoc);
@@ -1108,9 +1104,8 @@ private:
         _loKitDocument->registerCallback(ViewCallback, _viewIdToCallbackDescr[viewId].get());
 
         const int viewCount = _loKitDocument->getViewsCount();
-        LOG_INF("Document [" << _url << "] view [" <<
-                  viewId << "] loaded. Have " << viewCount <<
-                  " view" << (viewCount != 1 ? "s." : "."));
+        LOG_INF("Document [" << _url << "] view [" << viewId << "] loaded. Have " <<
+                viewCount << " view" << (viewCount != 1 ? "s." : "."));
 
         return _loKitDocument;
     }
@@ -1172,7 +1167,7 @@ private:
     {
         Util::setThreadName("lok_handler");
 
-        Log::debug("Thread started.");
+        LOG_DBG("Thread started.");
 
         try
         {
@@ -1189,7 +1184,7 @@ private:
 
                 if (tokens[0] == "eof")
                 {
-                    Log::info("Received EOF. Finishing.");
+                    LOG_INF("Received EOF. Finishing.");
                     break;
                 }
 
@@ -1228,9 +1223,9 @@ private:
                             }
                             else
                             {
-                                Log::error() << "Session thread for session " << session->getId() << " for view "
-                                             << viewId << " is not running. Dropping [" << LOKitHelper::kitCallbackTypeToString(type)
-                                             << "] payload [" << payload << "]." << Log::end;
+                                LOG_ERR("Session thread for session " << session->getId() << " for view " <<
+                                        viewId << " is not running. Dropping [" << LOKitHelper::kitCallbackTypeToString(type) <<
+                                        "] payload [" << payload << "].");
                             }
 
                             break;
@@ -1239,23 +1234,23 @@ private:
 
                     if (!isFound)
                     {
-                        Log::warn() << "Document::ViewCallback. The message [" << viewId
-                                    << "] [" << LOKitHelper::kitCallbackTypeToString(type)
-                                    << "] [" << payload << "] is not sent to Master Session." << Log::end;
+                        LOG_WRN("Document::ViewCallback. The message [" << viewId <<
+                                "] [" << LOKitHelper::kitCallbackTypeToString(type) <<
+                                "] [" << payload << "] is not sent to Master Session.");
                     }
                 }
                 else
                 {
-                    Log::error("Unexpected tile request: [" + message + "].");
+                    LOG_ERR("Unexpected tile request: [" << message << "].");
                 }
             }
         }
         catch (const std::exception& exc)
         {
-            Log::error(std::string("QueueHandler::run: Exception: ") + exc.what());
+            LOG_ERR("QueueHandler::run: Exception: " << exc.what());
         }
 
-        Log::debug("Thread finished.");
+        LOG_DBG("Thread finished.");
     }
 
 private:
@@ -1330,7 +1325,7 @@ void lokit_main(const std::string& childRoot,
 
     Util::setThreadName("loolkit");
 
-    Log::debug("Process started.");
+    LOG_DBG("Process started.");
 
     Util::setTerminationSignals();
     Util::setFatalSignals();
@@ -1343,7 +1338,7 @@ void lokit_main(const std::string& childRoot,
     try
     {
         jailPath = Path::forDirectory(childRoot + "/" + jailId);
-        Log::info("Jail path: " + jailPath.toString());
+        LOG_INF("Jail path: " << jailPath.toString());
         File(jailPath).createDirectories();
 
         if (bRunInsideJail)
@@ -1380,9 +1375,9 @@ void lokit_main(const std::string& childRoot,
                     usrSrcPath.toString() +
                     std::string(" ") +
                     usrDestPath.toString();
-                Log::debug("Initializing jail bind mount.");
+                LOG_DBG("Initializing jail bind mount.");
                 bLoopMounted = !system(mountCommand.c_str());
-                Log::debug("Initialized jail bind mount.");
+                LOG_DBG("Initialized jail bind mount.");
             }
             linkOrCopy(sysTemplate, jailPath,
                        bLoopMounted ? COPY_NO_USR : COPY_ALL);
@@ -1400,7 +1395,7 @@ void lokit_main(const std::string& childRoot,
                 }
             }
 
-            Log::debug("Initialized jail files.");
+            LOG_DBG("Initialized jail files.");
 
             // Create the urandom and random devices
             File(Path(jailPath, "/dev")).createDirectory();
@@ -1417,7 +1412,7 @@ void lokit_main(const std::string& childRoot,
                 Log::syserror("mknod(" + jailPath.toString() + "/dev/urandom) failed.");
             }
 
-            Log::info("chroot(\"" + jailPath.toString() + "\")");
+            LOG_INF("chroot(\"" << jailPath.toString() << "\")");
             if (chroot(jailPath.toString().c_str()) == -1)
             {
                 Log::syserror("chroot(\"" + jailPath.toString() + "\") failed.");
@@ -1434,11 +1429,11 @@ void lokit_main(const std::string& childRoot,
             dropCapability(CAP_MKNOD);
             dropCapability(CAP_FOWNER);
 
-            Log::debug("Initialized jail nodes, dropped caps.");
+            LOG_DBG("Initialized jail nodes, dropped caps.");
         }
         else // noCapabilities set
         {
-            Log::info("Using template " + loTemplate + " as install subpath - skipping jail setup");
+            LOG_INF("Using template " << loTemplate << " as install subpath - skipping jail setup");
             userdir_url = "file:///" + jailPath.toString() + "/user";
             instdir_path = "/" + loTemplate + "/program";
         }
@@ -1456,13 +1451,13 @@ void lokit_main(const std::string& childRoot,
             loKit = std::make_shared<lok::Office>(kit);
             if (!loKit || !loKit->get())
             {
-                Log::fatal("LibreOfficeKit initialization failed. Exiting.");
+                LOG_FTL("LibreOfficeKit initialization failed. Exiting.");
                 std::_Exit(Application::EXIT_SOFTWARE);
             }
         }
 
         assert(loKit && loKit->get());
-        Log::info("Process is ready.");
+        LOG_INF("Process is ready.");
 
         // Open websocket connection between the child process and WSD.
         HTTPClientSession cs("127.0.0.1", MasterPortNumber);
@@ -1497,13 +1492,13 @@ void lokit_main(const std::string& childRoot,
                     if (UnitKit::get().filterKitMessage(ws, message))
                         return true;
 
-                    Log::debug(socketName + ": recv [" + LOOLProtocol::getAbbreviatedMessage(message) + "].");
+                    LOG_DBG(socketName << ": recv [" << LOOLProtocol::getAbbreviatedMessage(message) << "].");
                     StringTokenizer tokens(message, " ", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
 
                     // Note: Syntax or parsing errors here are unexpected and fatal.
                     if (TerminationFlag)
                     {
-                        Log::debug("Too late, we're going down");
+                        LOG_DBG("Too late, we're going down");
                     }
                     else if (tokens[0] == "session")
                     {
@@ -1512,7 +1507,7 @@ void lokit_main(const std::string& childRoot,
 
                         std::string url;
                         URI::decode(docKey, url);
-                        Log::info("New session [" + sessionId + "] request on url [" + url + "].");
+                        LOG_INF("New session [" << sessionId << "] request on url [" << url << "].");
 
                         if (!document)
                         {
@@ -1523,7 +1518,7 @@ void lokit_main(const std::string& childRoot,
                         if (!(url == document->getUrl() &&
                               document->createSession(sessionId)))
                         {
-                            Log::debug("CreateSession failed.");
+                            LOG_DBG("CreateSession failed.");
                         }
                     }
                     else if (tokens[0] == "tile" || tokens[0] == "tilecombine" || tokens[0] == "canceltiles" ||
@@ -1535,17 +1530,17 @@ void lokit_main(const std::string& childRoot,
                         }
                         else
                         {
-                            Log::warn("No document while processing " + tokens[0] + " request.");
+                            LOG_WRN("No document while processing " << tokens[0] << " request.");
                         }
                     }
                     else if (document && document->canDiscard())
                     {
-                        Log::info("Last session discarded. Terminating.");
+                        LOG_INF("Last session discarded. Terminating.");
                         TerminationFlag = true;
                     }
                     else
                     {
-                        Log::error("Bad or unknown token [" + tokens[0] + "]");
+                        LOG_ERR("Bad or unknown token [" << tokens[0] << "]");
                     }
 
                     return true;
@@ -1555,7 +1550,7 @@ void lokit_main(const std::string& childRoot,
                 {
                     if (document && document->canDiscard())
                     {
-                        Log::info("Last session discarded. Terminating.");
+                        LOG_INF("Last session discarded. Terminating.");
                         TerminationFlag = true;
                     }
 
@@ -1566,18 +1561,17 @@ void lokit_main(const std::string& childRoot,
     }
     catch (const Exception& exc)
     {
-        Log::error() << "Poco Exception: " << exc.displayText()
-                     << (exc.nested() ? " (" + exc.nested()->displayText() + ")" : "")
-                     << Log::end;
+        LOG_ERR("Poco Exception: " << exc.displayText() <<
+                (exc.nested() ? " (" + exc.nested()->displayText() + ")" : ""));
     }
     catch (const std::exception& exc)
     {
-        Log::error(std::string("Exception: ") + exc.what());
+        LOG_ERR("Exception: " << exc.what());
     }
 
     // Trap the signal handler, if invoked,
     // to prevent exiting.
-    Log::info("Process finished.");
+    LOG_INF("Process finished.");
     std::unique_lock<std::mutex> lock(SigHandlerTrap);
     std::_Exit(Application::EXIT_OK);
 }
@@ -1593,11 +1587,11 @@ bool globalPreinit(const std::string &loTemplate)
     void *handle;
     if (File(libMerged).exists())
     {
-        Log::trace("dlopen(" + libMerged + ", RTLD_GLOBAL|RTLD_NOW)");
+        LOG_TRC("dlopen(" << libMerged << ", RTLD_GLOBAL|RTLD_NOW)");
         handle = dlopen(libMerged.c_str(), RTLD_GLOBAL|RTLD_NOW);
         if (!handle)
         {
-            Log::fatal("Failed to load " + libMerged + ": " + std::string(dlerror()));
+            LOG_FTL("Failed to load " << libMerged << ": " << dlerror());
             return false;
         }
         loadedLibrary = libMerged;
@@ -1606,18 +1600,18 @@ bool globalPreinit(const std::string &loTemplate)
     {
         if (File(libSofficeapp).exists())
         {
-            Log::trace("dlopen(" + libSofficeapp + ", RTLD_GLOBAL|RTLD_NOW)");
+            LOG_TRC("dlopen(" << libSofficeapp << ", RTLD_GLOBAL|RTLD_NOW)");
             handle = dlopen(libSofficeapp.c_str(), RTLD_GLOBAL|RTLD_NOW);
             if (!handle)
             {
-                Log::fatal("Failed to load " + libSofficeapp + ": " + std::string(dlerror()));
+                LOG_FTL("Failed to load " << libSofficeapp << ": " << dlerror());
                 return false;
             }
             loadedLibrary = libSofficeapp;
         }
         else
         {
-            Log::fatal("Neither " + libSofficeapp + " or " + libMerged + " exist.");
+            LOG_FTL("Neither " << libSofficeapp << " or " << libMerged << " exist.");
             return false;
         }
     }
@@ -1625,14 +1619,14 @@ bool globalPreinit(const std::string &loTemplate)
     LokHookPreInit* preInit = (LokHookPreInit *)dlsym(handle, "lok_preinit");
     if (!preInit)
     {
-        Log::fatal("No lok_preinit symbol in " + loadedLibrary + ": " + std::string(dlerror()));
+        LOG_FTL("No lok_preinit symbol in " << loadedLibrary << ": " << dlerror());
         return false;
     }
 
-    Log::trace("lok_preinit(" + loTemplate + "/program\", \"file:///user\")");
+    LOG_TRC("lok_preinit(" << loTemplate << "/program\", \"file:///user\")");
     if (preInit((loTemplate + "/program").c_str(), "file:///user") != 0)
     {
-        Log::fatal("lok_preinit() in " + loadedLibrary + " failed");
+        LOG_FTL("lok_preinit() in " << loadedLibrary << " failed");
         return false;
     }
 
commit 2c518bd6b7f9c49de140a9ae063c8556915919a6
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 12:52:31 2016 -0500

    loolwsd: UnitStorage logs updated
    
    Change-Id: Ie5e9bed6d6ab56039d357dea09470953ca49d458
    Reviewed-on: https://gerrit.libreoffice.org/30635
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit e329f3595f788798e77af40f28910fb1b4f65454)

diff --git a/loolwsd/test/UnitStorage.cpp b/loolwsd/test/UnitStorage.cpp
index 164e1e1..521786e 100644
--- a/loolwsd/test/UnitStorage.cpp
+++ b/loolwsd/test/UnitStorage.cpp
@@ -10,6 +10,7 @@
 #include <iostream>
 
 #include "Exceptions.hpp"
+#include "Log.hpp"
 #include "Unit.hpp"
 #include "UnitHTTP.hpp"
 #include "helpers.hpp"
@@ -36,8 +37,8 @@ public:
     {
         if (_phase == PHASE_FILTER)
         {
-            std::cerr << "throw low disk space exception" << std::endl;
             _phase = PHASE_RE_LOAD;
+            LOG_INF("Throwing low disk space exception.");
             throw StorageSpaceLowException("test: low disk space");
         }
         return false;
commit 51eaf8ae34693372d79a7ace0f96a3d0938cc119
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 12:10:43 2016 -0500

    loolwsd: UnitPrefork logs updated
    
    Change-Id: I7cc37295459aceac6ba38af4fb274c39f55885a4
    Reviewed-on: https://gerrit.libreoffice.org/30634
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit 10659d970befb63df2583d2627beb6c5ab9fb98e)

diff --git a/loolwsd/test/UnitPrefork.cpp b/loolwsd/test/UnitPrefork.cpp
index 3407e6b..e6837f5 100644
--- a/loolwsd/test/UnitPrefork.cpp
+++ b/loolwsd/test/UnitPrefork.cpp
@@ -69,7 +69,7 @@ public:
         }
         else
         {
-            Log::info("Got memory stats [" + memory + "].");
+            LOG_INF("Got memory stats [" << memory << "].");
             assert(tokens.count() == 2);
             _childPSS = atoi(tokens[0].c_str());
             _childDirty = atoi(tokens[1].c_str());
@@ -86,20 +86,21 @@ public:
         std::unique_lock<std::mutex> lock(_mutex);
 
         _childSockets.push_back(socket);
+        LOG_INF("Unit-prefork: got new child, have " << _childSockets.size() << " of " << NumToPrefork);
+
         if (_childSockets.size() >= NumToPrefork)
         {
             Poco::Timestamp::TimeDiff elapsed = _startTime.elapsed();
 
             const auto totalTime = (1000. * elapsed)/Poco::Timestamp::resolution();
-            Log::info() << "Launched " << _childSockets.size() << " in "
-                        << totalTime << Log::end;
+            LOG_INF("Launched " << _childSockets.size() << " in " << totalTime);
             size_t totalPSSKb = 0;
             size_t totalDirtyKb = 0;
 
             // Skip the last one as it's not completely initialized yet.
             for (size_t i = 0; i < _childSockets.size() - 1; ++i)
             {
-                Log::info() << "Getting memory of child #" << i + 1 << " of " << _childSockets.size() << Log::end;
+                LOG_INF("Getting memory of child #" << i + 1 << " of " << _childSockets.size());
 
                 _childSockets[i]->sendFrame("unit-memdump: \n", sizeof("unit-memdump: \n"));
                 if (_cv.wait_for(lock, std::chrono::milliseconds(5 * 1000)) == std::cv_status::timeout)
@@ -181,10 +182,10 @@ namespace
         std::ostringstream oss;
         oss << numPSSKb << " " << numDirtyKb;
         const auto res = oss.str();
-        Log::info("readMemorySize: [" + res + "].");
+        LOG_INF("readMemorySize: [" << res << "].");
         if (res.empty())
         {
-            Log::error("Failed to read memory stats.");
+            LOG_ERR("Failed to read memory stats.");
             throw std::runtime_error("Failed to read memory stats.");
         }
 
@@ -239,7 +240,7 @@ public:
                 assert(len<sizeof(buffer));
                 numSockets++;
                 char *extDot = strrchr(buffer, '.');
-                Log::info() << "fd:" << ent->d_name << " -> " << buffer << Log::end;
+                LOG_INF("fd:" << ent->d_name << " -> " << buffer);
                 if (!strncmp(buffer, "/dev/", sizeof ("/dev/") -1))
                     deviceCount++;
                 else if (extDot && !strcmp(extDot, ".res"))
@@ -305,7 +306,7 @@ public:
                 memory = _failure;
             else
                 memory = readMemorySizes(_procSMaps);
-            Log::info("filterKitMessage sending back: [" + memory + "].");
+            LOG_INF("filterKitMessage sending back: [" << memory << "].");
             ws->sendFrame(memory.c_str(), memory.length());
             return true;
         }
commit f2be41991e0d02b3dfea8d0e3626eee3d1d6e552
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 12:06:21 2016 -0500

    loolwsd: Unit logs updated
    
    Change-Id: Ic60e59f21bdb426997808d14a4e0375e38362161
    Reviewed-on: https://gerrit.libreoffice.org/30633
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit ca17fc74c753fd24447545da824ca29757609005)

diff --git a/loolwsd/Unit.cpp b/loolwsd/Unit.cpp
index 43c9e9a..f269fc7 100644
--- a/loolwsd/Unit.cpp
+++ b/loolwsd/Unit.cpp
@@ -31,7 +31,7 @@ UnitBase *UnitBase::linkAndCreateUnit(UnitType type, const std::string &unitLibP
     void *dlHandle = dlopen(unitLibPath.c_str(), RTLD_GLOBAL|RTLD_NOW);
     if (!dlHandle)
     {
-        Log::error("Failed to load " + unitLibPath + ": " + std::string(dlerror()));
+        LOG_ERR("Failed to load " << unitLibPath << ": " << dlerror());
         return NULL;
     }
 
@@ -49,7 +49,7 @@ UnitBase *UnitBase::linkAndCreateUnit(UnitType type, const std::string &unitLibP
     createHooks = reinterpret_cast<CreateUnitHooksFunction *>(dlsym(dlHandle, symbol));
     if (!createHooks)
     {
-        Log::error("No " + std::string(symbol) + " symbol in " + unitLibPath);
+        LOG_ERR("No " << symbol << " symbol in " << unitLibPath);
         return NULL;
     }
     UnitBase *pHooks = createHooks();
@@ -72,7 +72,7 @@ bool UnitBase::init(UnitType type, const std::string &unitLibPath)
                     TimeoutThread.trySleep(Global->_timeoutMilliSeconds);
                     if (!Global->_timeoutShutdown)
                     {
-                        Log::error("Unit test timeout");
+                        LOG_ERR("Unit test timeout");
                         Global->timeout();
                     }
                 });
commit caa275f4c9a6a08e9bd606f09d3f757ce517d22f
Author: Ashod Nakashian <ashod.nakashian at collabora.co.uk>
Date:   Sun Nov 6 11:59:59 2016 -0500

    loolwsd: DocumentBroker logs updated
    
    Change-Id: I64bd10c05a24f1b6716241cf1048af157282fa18
    Reviewed-on: https://gerrit.libreoffice.org/30632
    Reviewed-by: Ashod Nakashian <ashnakash at gmail.com>
    Tested-by: Ashod Nakashian <ashnakash at gmail.com>
    (cherry picked from commit 9bb6d73fdad7b16382a4cf03d6c826e1810cff19)

diff --git a/loolwsd/DocumentBroker.cpp b/loolwsd/DocumentBroker.cpp
index 507362c..cf66a4a 100644
--- a/loolwsd/DocumentBroker.cpp
+++ b/loolwsd/DocumentBroker.cpp
@@ -115,29 +115,6 @@ std::string DocumentBroker::getDocKey(const Poco::URI& uri)
     return docKey;
 }
 
-DocumentBroker::DocumentBroker() :
-    _uriPublic(),
-    _docKey(),
-    _childRoot(),
-    _cacheRoot(),
-    _childProcess(),
-    _lastSaveTime(std::chrono::steady_clock::now()),
-    _markToDestroy(true),
-    _lastEditableSession(true),
-    _isLoaded(false),
-    _isModified(false),
-    _cursorPosX(0),
-    _cursorPosY(0),
-    _cursorWidth(0),
-    _cursorHeight(0),
-    _mutex(),
-    _saveMutex(),
-    _tileVersion(0),
-    _debugRenderedTileCount(0)
-{
-    Log::info("Empty DocumentBroker (marked to destroy) created.");
-}
-
 DocumentBroker::DocumentBroker(const Poco::URI& uriPublic,
                                const std::string& docKey,
                                const std::string& childRoot,
@@ -164,8 +141,7 @@ DocumentBroker::DocumentBroker(const Poco::URI& uriPublic,
     assert(!_docKey.empty());
     assert(!_childRoot.empty());
 
-    LOG_INF("DocumentBroker [" << _uriPublic.toString() <<
-            "] created. DocKey: [" << _docKey << "]");
+    LOG_INF("DocumentBroker [" << _uriPublic.toString() << "] created. DocKey: [" << _docKey << "]");
 }
 
 DocumentBroker::~DocumentBroker()
@@ -173,8 +149,7 @@ DocumentBroker::~DocumentBroker()
     Admin::instance().rmDoc(_docKey);
 
     LOG_INF("~DocumentBroker [" << _uriPublic.toString() <<
-            "] destroyed with " << _sessions.size() <<
-            " sessions left.");
+            "] destroyed with " << _sessions.size() << " sessions left.");
 
     if (!_sessions.empty())
     {
@@ -203,12 +178,12 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
     auto it = _sessions.find(sessionId);
     if (it == _sessions.end())
     {
-        Log::error("Session with sessionId [" + sessionId + "] not found while loading");
+        LOG_ERR("Session with sessionId [" << sessionId << "] not found while loading");
         return false;
     }
 
     const Poco::URI& uriPublic = it->second->getPublicUri();
-    Log::debug("Loading from URI: " + uriPublic.toString());
+    LOG_DBG("Loading from URI: " << uriPublic.toString());
 
     _jailId = jailId;
 
@@ -219,7 +194,7 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
     const auto jailPath = Poco::Path(JAILED_DOCUMENT_ROOT, jailId);
     std::string jailRoot = getJailRoot();
 
-    Log::info("jailPath: " + jailPath.toString() + ", jailRoot: " + jailRoot);
+    LOG_INF("jailPath: " << jailPath.toString() << ", jailRoot: " << jailRoot);
 
     if (LOOLWSD::NoCapsForKit)
         jailRoot = jailPath.toString() + "/" + getJailRoot();
@@ -229,7 +204,7 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
         // TODO: Maybe better to pass docKey to storage here instead of uriPublic here because
         // uriPublic would be different for each view of the document (due to
         // different query params like access token etc.)
-        Log::debug("Creating new storage instance for URI [" + uriPublic.toString() + "].");
+        LOG_DBG("Creating new storage instance for URI [" << uriPublic.toString() << "].");
         _storage = StorageBase::create(uriPublic, jailRoot, jailPath.toString());
     }
 
@@ -246,7 +221,7 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
 
             if (!wopifileinfo._userCanWrite)
             {
-                Log::debug("Setting the session as readonly");
+                LOG_DBG("Setting the session as readonly");
                 it->second->setReadOnly();
             }
 
@@ -264,7 +239,7 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
             username = localfileinfo._username;
         }
 
-        Log::debug("Setting username [" + username + "] and userId [" + userid + "] for session [" + sessionId + "]");
+        LOG_DBG("Setting username [" << username << "] and userId [" << userid << "] for session [" << sessionId << "]");
         it->second->setUserId(userid);
         it->second->setUserName(username);
 
@@ -272,7 +247,7 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
         const auto fileInfo = _storage->getFileInfo();
         if (!fileInfo.isValid())
         {
-            Log::error("Invalid fileinfo for URI [" + uriPublic.toString() + "].");
+            LOG_ERR("Invalid fileinfo for URI [" << uriPublic.toString() << "].");
             return false;
         }
 
@@ -297,7 +272,7 @@ bool DocumentBroker::load(const std::string& sessionId, const std::string& jailI
             // Add the time taken to check file info
             callDuration += getInfoCallDuration;
             const std::string msg = "stats: wopiloadduration " + std::to_string(callDuration.count());
-            Log::trace("Sending to Client [" + msg + "].");
+            LOG_TRC("Sending to Client [" << msg << "].");
             it->second->sendTextFrame(msg);
         }
 
@@ -314,7 +289,7 @@ bool DocumentBroker::save(const std::string& sessionId, bool success, const std:
     const auto it = _sessions.find(sessionId);
     if (it == _sessions.end())
     {
-        Log::error("Session with sessionId [" + sessionId + "] not found while saving");
+        LOG_ERR("Session with sessionId [" << sessionId << "] not found while saving");
         return false;
     }
 
@@ -325,7 +300,7 @@ bool DocumentBroker::save(const std::string& sessionId, bool success, const std:
     // notify the waiting thread, if any.
     if (!success && result == "unmodified")
     {
-        Log::debug("Save skipped as document was not modified");
+        LOG_DBG("Save skipped as document was not modified");
         _saveCV.notify_all();
         return true;
     }
@@ -336,14 +311,12 @@ bool DocumentBroker::save(const std::string& sessionId, bool success, const std:
     if (!_lastEditableSession && newFileModifiedTime == _lastFileModifiedTime)
     {
         // Nothing to do.
-        Log::debug() << "Skipping unnecessary saving to URI [" << uri
-                     << "]. File last modified "
-                     << _lastFileModifiedTime.elapsed() / 1000000
-                     << " seconds ago." << Log::end;
+        LOG_DBG("Skipping unnecessary saving to URI [" << uri << "]. File last modified " <<
+                _lastFileModifiedTime.elapsed() / 1000000 << " seconds ago.");
         return true;
     }
 
-    Log::debug("Saving to URI [" + uri + "].");
+    LOG_DBG("Saving to URI [" << uri << "].");
 
     assert(_storage && _tileCache);
     if (_storage->saveLocalFileToStorage(uriPublic))
@@ -353,12 +326,12 @@ bool DocumentBroker::save(const std::string& sessionId, bool success, const std:
         _lastFileModifiedTime = newFileModifiedTime;
         _tileCache->saveLastModified(_lastFileModifiedTime);
         _lastSaveTime = std::chrono::steady_clock::now();
-        Log::debug("Saved to URI [" + uri + "] and updated tile cache.");
+        LOG_DBG("Saved to URI [" << uri << "] and updated tile cache.");
         _saveCV.notify_all();
         return true;
     }
 
-    Log::error("Failed to save to URI [" + uri + "].");
+    LOG_ERR("Failed to save to URI [" << uri << "].");
     return false;
 }
 
@@ -370,18 +343,18 @@ bool DocumentBroker::autoSave(const bool force, const size_t waitTimeoutMs, std:
         !_childProcess->isAlive() || (!_isModified && !force))
     {
         // Nothing to do.
-        Log::trace("Nothing to autosave [" + _docKey + "].");
+        LOG_TRC("Nothing to autosave [" << _docKey << "].");
         return true;
     }
 
     // Remeber the last save time, since this is the predicate.
     const auto lastSaveTime = _lastSaveTime;
-    Log::trace("Checking to autosave [" + _docKey + "].");
+    LOG_TRC("Checking to autosave [" << _docKey << "].");
 
     bool sent = false;
     if (force)
     {
-        Log::trace("Sending forced save command for [" + _docKey + "].");
+        LOG_TRC("Sending forced save command for [" << _docKey << "].");
         sent = sendUnoSave(true);
     }
     else if (_isModified)
@@ -393,25 +366,25 @@ bool DocumentBroker::autoSave(const bool force, const size_t waitTimeoutMs, std:
             inactivityTimeMs = std::min(sessionIt.second->getInactivityMS(), inactivityTimeMs);
         }
 
-        Log::trace("Most recent activity was " + std::to_string((int)inactivityTimeMs) + " ms ago.");
+        LOG_TRC("Most recent activity was " << inactivityTimeMs << " ms ago.");
         const auto timeSinceLastSaveMs = getTimeSinceLastSaveMs();
-        Log::trace("Time since last save is " + std::to_string((int)timeSinceLastSaveMs) + " ms.");
+        LOG_TRC("Time since last save is " << timeSinceLastSaveMs << " ms.");
 
         // Either we've been idle long enough, or it's auto-save time.
         if (inactivityTimeMs >= IdleSaveDurationMs ||
             timeSinceLastSaveMs >= AutoSaveDurationMs)
         {
-            Log::trace("Sending timed save command for [" + _docKey + "].");
+            LOG_TRC("Sending timed save command for [" << _docKey << "].");
             sent = sendUnoSave(true);
         }
     }
 
     if (sent && waitTimeoutMs > 0)
     {
-        Log::trace("Waiting for save event for [" + _docKey + "].");
+        LOG_TRC("Waiting for save event for [" << _docKey << "].");
         if (_saveCV.wait_for(lock, std::chrono::milliseconds(waitTimeoutMs)) == std::cv_status::no_timeout)
         {
-            Log::debug("Successfully persisted document [" + _docKey + "] or document was not modified");
+            LOG_DBG("Successfully persisted document [" << _docKey << "] or document was not modified");
             return true;
         }
 
@@ -423,7 +396,7 @@ bool DocumentBroker::autoSave(const bool force, const size_t waitTimeoutMs, std:
 
 bool DocumentBroker::sendUnoSave(const bool dontSaveIfUnmodified)
 {
-    Log::info("Autosave triggered for doc [" + _docKey + "].");
+    LOG_INF("Autosave triggered for doc [" << _docKey << "].");
     Util::assertIsLocked(_mutex);
 
     // Save using session holding the edit-lock (or first if multview).
@@ -460,13 +433,13 @@ bool DocumentBroker::sendUnoSave(const bool dontSaveIfUnmodified)
         oss << "}";
 
         const auto saveArgs = oss.str();
-        Log::trace(".uno:Save arguments: " + saveArgs);
+        LOG_TRC(".uno:Save arguments: " << saveArgs);
         const auto command = "uno .uno:Save " + saveArgs;
         forwardToChild(sessionIt.second->getId(), command);
         return true;
     }
 
-    Log::error("Failed to auto-save doc [" + _docKey + "]: No valid sessions.");
+    LOG_ERR("Failed to auto-save doc [" << _docKey << "]: No valid sessions.");
     return false;
 }
 
@@ -491,12 +464,12 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
         auto ret = _sessions.emplace(id, session);
         if (!ret.second)
         {
-            Log::warn("DocumentBroker: Trying to add already existing session.");
+            LOG_WRN("DocumentBroker: Trying to add already existing session.");
         }
 
         if (session->isReadOnly())
         {
-            Log::debug("Adding a readonly session [" + id + "]");
+            LOG_DBG("Adding a readonly session [" << id << "]");
         }
 
         // Below values are recalculated when startDestroy() is called (before destroying the
@@ -509,7 +482,7 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
         if (!loaded)
         {
             const auto msg = "Failed to load document with URI [" + session->getPublicUri().toString() + "].";
-            Log::error(msg);
+            LOG_ERR(msg);
             throw std::runtime_error(msg);
         }
     }
@@ -531,7 +504,7 @@ size_t DocumentBroker::addSession(std::shared_ptr<ClientSession>& session)
     // Connect the prison session to the client.
     if (!connectPeers(prisonerSession))
     {
-        Log::warn("Failed to connect " + session->getName() + " to its peer.");
+        LOG_WRN("Failed to connect " << session->getName() << " to its peer.");
     }
 
     return _sessions.size();
@@ -587,7 +560,7 @@ void DocumentBroker::alertAllUsersOfDocument(const std::string& cmd, const std::
 bool DocumentBroker::handleInput(const std::vector<char>& payload)
 {
     const auto msg = LOOLProtocol::getAbbreviatedMessage(payload);
-    Log::trace("DocumentBroker got child message: [" + msg + "].");
+    LOG_TRC("DocumentBroker got child message: [" << msg << "].");
 
     LOOLWSD::dumpOutgoingTrace(getJailId(), "0", msg);
 
@@ -617,7 +590,7 @@ bool DocumentBroker::handleInput(const std::vector<char>& payload)
     }
     else
     {
-        Log::error("Unexpected message: [" + msg + "].");
+        LOG_ERR("Unexpected message: [" << msg << "].");
         return false;
     }
 
@@ -639,7 +612,7 @@ void DocumentBroker::handleTileRequest(TileDesc& tile,
 
     tile.setVersion(++_tileVersion);
     const auto tileMsg = tile.serialize();
-    Log::trace() << "Tile request for " << tile.serialize() << Log::end;
+    LOG_TRC("Tile request for " << tile.serialize());
 
     std::unique_ptr<std::fstream> cachedTile = _tileCache->lookupTile(tile);
     if (cachedTile)
@@ -671,8 +644,8 @@ void DocumentBroker::handleTileRequest(TileDesc& tile,
     tileCache().subscribeToTileRendering(tile, session);
 
     // Forward to child to render.
-    Log::debug() << "Sending render request for tile (" << tile.getPart() << ','
-                 << tile.getTilePosX() << ',' << tile.getTilePosY() << ")." << Log::end;
+    LOG_DBG("Sending render request for tile (" << tile.getPart() << ',' <<
+            tile.getTilePosX() << ',' << tile.getTilePosY() << ").");
     const std::string request = "tile " + tile.serialize();
     _childProcess->sendTextFrame(request);
     _debugRenderedTileCount++;
@@ -683,7 +656,7 @@ void DocumentBroker::handleTileCombinedRequest(TileCombined& tileCombined,
 {
     std::unique_lock<std::mutex> lock(_mutex);
 
-    Log::trace() << "TileCombined request for " << tileCombined.serialize() << Log::end;
+    LOG_TRC("TileCombined request for " << tileCombined.serialize());
 
     // Satisfy as many tiles from the cache.
     std::vector<TileDesc> tiles;
@@ -732,7 +705,7 @@ void DocumentBroker::handleTileCombinedRequest(TileCombined& tileCombined,
 
         // Forward to child to render.
         const auto req = newTileCombined.serialize("tilecombine");
-        Log::debug() << "Sending residual tilecombine: " << req << Log::end;
+        LOG_DBG("Sending residual tilecombine: " << req);
         _childProcess->sendTextFrame(req);
     }
 }
@@ -744,7 +717,7 @@ void DocumentBroker::cancelTileRequests(const std::shared_ptr<ClientSession>& se
     const auto canceltiles = tileCache().cancelTiles(session);
     if (!canceltiles.empty())
     {
-        Log::debug() << "Forwarding canceltiles request: " << canceltiles << Log::end;
+        LOG_DBG("Forwarding canceltiles request: " << canceltiles);
         _childProcess->sendTextFrame(canceltiles);
     }
 }
@@ -752,7 +725,7 @@ void DocumentBroker::cancelTileRequests(const std::shared_ptr<ClientSession>& se
 void DocumentBroker::handleTileResponse(const std::vector<char>& payload)
 {
     const std::string firstLine = getFirstLine(payload);
-    Log::debug("Handling tile combined: " + firstLine);
+    LOG_DBG("Handling tile combined: " << firstLine);
 
     try
     {
@@ -766,20 +739,20 @@ void DocumentBroker::handleTileResponse(const std::vector<char>& payload)
         }
         else
         {
-            Log::debug() << "Render request declined for " << firstLine << Log::end;
+            LOG_DBG("Render request declined for " << firstLine);
             // They will get re-issued if we don't forget them.
         }
     }
     catch (const std::exception& exc)
     {
-        Log::error("Failed to process tile response [" + firstLine + "]: " + exc.what() + ".");
+        LOG_ERR("Failed to process tile response [" << firstLine << "]: " << exc.what() << ".");
     }
 }
 

... etc. - the rest is truncated


More information about the Libreoffice-commits mailing list