util: logging facility

refs #3562

Change-Id: I61d934c5306e1a73b41c81aeb3524d6bf581af3c
diff --git a/.waf-tools/boost.py b/.waf-tools/boost.py
index 8c36b34..9b9395e 100644
--- a/.waf-tools/boost.py
+++ b/.waf-tools/boost.py
@@ -30,15 +30,15 @@
 
 Options are generated, in order to specify the location of boost includes/libraries.
 The `check_boost` configuration function allows to specify the used boost libraries.
-It can also provide default arguments to the --boost-static and --boost-mt command-line arguments.
+It can also provide default arguments to the --boost-mt command-line arguments.
 Everything will be packaged together in a BOOST component that you can use.
 
 When using MSVC, a lot of compilation flags need to match your BOOST build configuration:
  - you may have to add /EHsc to your CXXFLAGS or define boost::throw_exception if BOOST_NO_EXCEPTIONS is defined.
    Errors: C4530
  - boost libraries will try to be smart and use the (pretty but often not useful) auto-linking feature of MSVC
-   So before calling `conf.check_boost` you might want to disabling by adding:
-   	conf.env.DEFINES_BOOST += ['BOOST_ALL_NO_LIB']
+   So before calling `conf.check_boost` you might want to disabling by adding
+		conf.env.DEFINES_BOOST += ['BOOST_ALL_NO_LIB']
    Errors:
  - boost might also be compiled with /MT, which links the runtime statically.
    If you have problems with redefined symbols,
@@ -52,27 +52,55 @@
 import re
 from waflib import Utils, Logs, Errors
 from waflib.Configure import conf
+from waflib.TaskGen import feature, after_method
 
-BOOST_LIBS = ['/usr/lib', '/usr/local/lib', '/opt/local/lib', '/sw/lib', '/lib',
-              '/usr/lib/x86_64-linux-gnu', '/usr/lib/i386-linux-gnu',
-              '/usr/local/ndn/lib', '/opt/ndn/lib']
-BOOST_INCLUDES = ['/usr/include', '/usr/local/include', '/opt/local/include', '/sw/include',
-                  '/usr/local/ndn/include', '/opt/ndn/include']
+BOOST_LIBS = ['/usr/lib/x86_64-linux-gnu', '/usr/lib/i386-linux-gnu',
+			  '/usr/lib', '/usr/local/lib', '/opt/local/lib', '/sw/lib', '/lib']
+BOOST_INCLUDES = ['/usr/include', '/usr/local/include', '/opt/local/include', '/sw/include']
 BOOST_VERSION_FILE = 'boost/version.hpp'
 BOOST_VERSION_CODE = '''
 #include <iostream>
 #include <boost/version.hpp>
 int main() { std::cout << BOOST_LIB_VERSION << ":" << BOOST_VERSION << std::endl; }
 '''
-BOOST_SYSTEM_CODE = '''
+
+BOOST_ERROR_CODE = '''
 #include <boost/system/error_code.hpp>
 int main() { boost::system::error_code c; }
 '''
+
+PTHREAD_CODE = '''
+#include <pthread.h>
+static void* f(void*) { return 0; }
+int main() {
+	pthread_t th;
+	pthread_attr_t attr;
+	pthread_attr_init(&attr);
+	pthread_create(&th, &attr, &f, 0);
+	pthread_join(th, 0);
+	pthread_cleanup_push(0, 0);
+	pthread_cleanup_pop(0);
+	pthread_attr_destroy(&attr);
+}
+'''
+
 BOOST_THREAD_CODE = '''
 #include <boost/thread.hpp>
 int main() { boost::thread t; }
 '''
 
+BOOST_LOG_CODE = '''
+#include <boost/log/trivial.hpp>
+#include <boost/log/utility/setup/console.hpp>
+#include <boost/log/utility/setup/common_attributes.hpp>
+int main() {
+	using namespace boost::log;
+	add_common_attributes();
+	add_console_log(std::clog, keywords::format = "%Message%");
+	BOOST_LOG_TRIVIAL(debug) << "log is working" << std::endl;
+}
+'''
+
 # toolsets from {boost_dir}/tools/build/v2/tools/common.jam
 PLATFORM = Utils.unversioned_sys_platform()
 detect_intel = lambda env: (PLATFORM == 'win32') and 'iw' or 'il'
@@ -104,34 +132,37 @@
 
 def options(opt):
 	opt = opt.add_option_group('Boost Options')
-
 	opt.add_option('--boost-includes', type='string',
 				   default='', dest='boost_includes',
-				   help='''path to the directory where the boost includes are, e.g., /path/to/boost_1_55_0/stage/include''')
+				   help='''path to the directory where the boost includes are,
+				   e.g., /path/to/boost_1_55_0/stage/include''')
 	opt.add_option('--boost-libs', type='string',
 				   default='', dest='boost_libs',
-				   help='''path to the directory where the boost libs are, e.g., /path/to/boost_1_55_0/stage/lib''')
-	opt.add_option('--boost-static', action='store_true',
-				   default=False, dest='boost_static',
-				   help='link with static boost libraries (.lib/.a)')
+				   help='''path to the directory where the boost libs are,
+				   e.g., path/to/boost_1_55_0/stage/lib''')
 	opt.add_option('--boost-mt', action='store_true',
 				   default=False, dest='boost_mt',
 				   help='select multi-threaded libraries')
 	opt.add_option('--boost-abi', type='string', default='', dest='boost_abi',
-				   help='''select libraries with tags (dgsyp, d for debug), see doc Boost, Getting Started, chapter 6.1''')
+				   help='''select libraries with tags (gd for debug, static is automatically added),
+				   see doc Boost, Getting Started, chapter 6.1''')
 	opt.add_option('--boost-linkage_autodetect', action="store_true", dest='boost_linkage_autodetect',
 				   help="auto-detect boost linkage options (don't get used to it / might break other stuff)")
 	opt.add_option('--boost-toolset', type='string',
 				   default='', dest='boost_toolset',
-				   help='force a toolset e.g. msvc, vc90, gcc, mingw, mgw45 (default: auto)')
+				   help='force a toolset e.g. msvc, vc90, \
+						gcc, mingw, mgw45 (default: auto)')
 	py_version = '%d%d' % (sys.version_info[0], sys.version_info[1])
 	opt.add_option('--boost-python', type='string',
 				   default=py_version, dest='boost_python',
-				   help='select the lib python with this version (default: %s)' % py_version)
+				   help='select the lib python with this version \
+						(default: %s)' % py_version)
 
 
 @conf
 def __boost_get_version_file(self, d):
+	if not d:
+		return None
 	dnode = self.root.find_dir(d)
 	if dnode:
 		return dnode.find_node(BOOST_VERSION_FILE)
@@ -144,18 +175,15 @@
 	if node:
 		try:
 			txt = node.read()
-		except (OSError, IOError):
+		except EnvironmentError:
 			Logs.error("Could not read the file %r" % node.abspath())
 		else:
-			re_but1 = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.*)"', re.M)
+			re_but1 = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.+)"', re.M)
 			m1 = re_but1.search(txt)
-
-			re_but2 = re.compile('^#define\\s+BOOST_VERSION\\s+(\\d*)', re.M)
+			re_but2 = re.compile('^#define\\s+BOOST_VERSION\\s+(\\d+)', re.M)
 			m2 = re_but2.search(txt)
-
 			if m1 and m2:
 				return (m1.group(1), m2.group(1))
-
 	return self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[d], execute=True, define_ret=True).split(":")
 
 @conf
@@ -163,7 +191,7 @@
 	includes = k and k[0] or kw.get('includes', None)
 	if includes and self.__boost_get_version_file(includes):
 		return includes
-	for d in Utils.to_list(self.environ.get('INCLUDE', '')) + BOOST_INCLUDES:
+	for d in self.environ.get('INCLUDE', '').split(';') + BOOST_INCLUDES:
 		if self.__boost_get_version_file(d):
 			return d
 	if includes:
@@ -198,7 +226,9 @@
 		path = self.root.find_dir(libs)
 		files = path.ant_glob('*boost_*')
 	if not libs or not files:
-		for d in Utils.to_list(self.environ.get('LIB', [])) + BOOST_LIBS:
+		for d in self.environ.get('LIB', '').split(';') + BOOST_LIBS:
+			if not d:
+				continue
 			path = self.root.find_dir(d)
 			if path:
 				files = path.ant_glob('*boost_*')
@@ -229,15 +259,10 @@
 	according to the parameters
 	'''
 	path, files = self.__boost_get_libs_path(**kw)
-	t = []
-	if kw.get('mt', False):
-		t.append('mt')
-	if kw.get('abi', None):
-		t.append(kw['abi'])
-	tags = t and '(-%s)+' % '-'.join(t) or ''
+	files = sorted(files, key=lambda f: (len(f.name), f.name), reverse=True)
 	toolset = self.boost_get_toolset(kw.get('toolset', ''))
-	toolset_pat = '(-%s[0-9]{0,3})+' % toolset
-	version = '(-%s)+' % self.env.BOOST_VERSION
+	toolset_pat = '(-%s[0-9]{0,3})' % toolset
+	version = '-%s' % self.env.BOOST_VERSION
 
 	def find_lib(re_lib, files):
 		for file in files:
@@ -251,28 +276,110 @@
 			name = name[3:]
 		return name[:name.rfind('.')]
 
-	libs = []
-	for lib in Utils.to_list(k and k[0] or kw.get('lib', None)):
-		py = (lib == 'python') and '(-py%s)+' % kw['python'] or ''
-		# Trying libraries, from most strict match to least one
-		for pattern in ['boost_%s%s%s%s%s' % (lib, toolset_pat, tags, py, version),
-						'boost_%s%s%s%s' % (lib, tags, py, version),
-						'boost_%s%s%s' % (lib, tags, version),
-						# Give up trying to find the right version
-						'boost_%s%s%s%s' % (lib, toolset_pat, tags, py),
-						'boost_%s%s%s' % (lib, tags, py),
-						'boost_%s%s' % (lib, tags)]:
-			self.to_log('Trying pattern %s' % pattern)
-			file = find_lib(re.compile(pattern), files)
-			if file:
-				libs.append(format_lib_name(file.name))
-				break
-		else:
-			self.end_msg('lib %s not found in %s' % (lib, path.abspath()))
-			self.fatal('The configuration failed')
+	def match_libs(lib_names, is_static):
+		libs = []
+		lib_names = Utils.to_list(lib_names)
+		if not lib_names:
+			return libs
+		t = []
+		if kw.get('mt', False):
+			t.append('-mt')
+		if kw.get('abi', None):
+			t.append('%s%s' % (is_static and '-s' or '-', kw['abi']))
+		elif is_static:
+			t.append('-s')
+		tags_pat = t and ''.join(t) or ''
+		ext = is_static and self.env.cxxstlib_PATTERN or self.env.cxxshlib_PATTERN
+		ext = ext.partition('%s')[2] # remove '%s' or 'lib%s' from PATTERN
 
-	return path.abspath(), libs
+		for lib in lib_names:
+			if lib == 'python':
+				# for instance, with python='27',
+				# accepts '-py27', '-py2', '27' and '2'
+				# but will reject '-py3', '-py26', '26' and '3'
+				tags = '({0})?((-py{2})|(-py{1}(?=[^0-9]))|({2})|({1}(?=[^0-9]))|(?=[^0-9])(?!-py))'.format(tags_pat, kw['python'][0], kw['python'])
+			else:
+				tags = tags_pat
+			# Trying libraries, from most strict match to least one
+			for pattern in ['boost_%s%s%s%s%s$' % (lib, toolset_pat, tags, version, ext),
+							'boost_%s%s%s%s$' % (lib, tags, version, ext),
+							# Give up trying to find the right version
+							'boost_%s%s%s%s$' % (lib, toolset_pat, tags, ext),
+							'boost_%s%s%s$' % (lib, tags, ext),
+							'boost_%s%s$' % (lib, ext),
+							'boost_%s' % lib]:
+				self.to_log('Trying pattern %s' % pattern)
+				file = find_lib(re.compile(pattern), files)
+				if file:
+					libs.append(format_lib_name(file.name))
+					break
+			else:
+				self.end_msg('lib %s not found in %s' % (lib, path.abspath()))
+				self.fatal('The configuration failed')
+		return libs
 
+	return  path.abspath(), match_libs(kw.get('lib', None), False), match_libs(kw.get('stlib', None), True)
+
+@conf
+def _check_pthread_flag(self, *k, **kw):
+	'''
+	Computes which flags should be added to CXXFLAGS and LINKFLAGS to compile in multi-threading mode
+
+	Yes, we *need* to put the -pthread thing in CPPFLAGS because with GCC3,
+	boost/thread.hpp will trigger a #error if -pthread isn't used:
+	  boost/config/requires_threads.hpp:47:5: #error "Compiler threading support
+	  is not turned on. Please set the correct command line options for
+	  threading: -pthread (Linux), -pthreads (Solaris) or -mthreads (Mingw32)"
+
+	Based on _BOOST_PTHREAD_FLAG(): https://github.com/tsuna/boost.m4/blob/master/build-aux/boost.m4
+    '''
+
+	var = kw.get('uselib_store', 'BOOST')
+
+	self.start_msg('Checking the flags needed to use pthreads')
+
+	# The ordering *is* (sometimes) important.  Some notes on the
+	# individual items follow:
+	# (none): in case threads are in libc; should be tried before -Kthread and
+	#       other compiler flags to prevent continual compiler warnings
+	# -lpthreads: AIX (must check this before -lpthread)
+	# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
+	# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
+	# -llthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
+	# -pthread: GNU Linux/GCC (kernel threads), BSD/GCC (userland threads)
+	# -pthreads: Solaris/GCC
+	# -mthreads: MinGW32/GCC, Lynx/GCC
+	# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
+	#      doesn't hurt to check since this sometimes defines pthreads too;
+	#      also defines -D_REENTRANT)
+	#      ... -mt is also the pthreads flag for HP/aCC
+	# -lpthread: GNU Linux, etc.
+	# --thread-safe: KAI C++
+	if Utils.unversioned_sys_platform() == "sunos":
+		# On Solaris (at least, for some versions), libc contains stubbed
+		# (non-functional) versions of the pthreads routines, so link-based
+		# tests will erroneously succeed.  (We need to link with -pthreads/-mt/
+		# -lpthread.)  (The stubs are missing pthread_cleanup_push, or rather
+		# a function called by this macro, so we could check for that, but
+		# who knows whether they'll stub that too in a future libc.)  So,
+		# we'll just look for -pthreads and -lpthread first:
+		boost_pthread_flags = ["-pthreads", "-lpthread", "-mt", "-pthread"]
+	else:
+		boost_pthread_flags = ["", "-lpthreads", "-Kthread", "-kthread", "-llthread", "-pthread",
+							   "-pthreads", "-mthreads", "-lpthread", "--thread-safe", "-mt"]
+
+	for boost_pthread_flag in boost_pthread_flags:
+		try:
+			self.env.stash()
+			self.env['CXXFLAGS_%s' % var] += [boost_pthread_flag]
+			self.env['LINKFLAGS_%s' % var] += [boost_pthread_flag]
+			self.check_cxx(code=PTHREAD_CODE, msg=None, use=var, execute=False)
+
+			self.end_msg(boost_pthread_flag)
+			return
+		except self.errors.ConfigurationError:
+			self.env.revert()
+	self.end_msg('None')
 
 @conf
 def check_boost(self, *k, **kw):
@@ -285,7 +392,10 @@
 	if not self.env['CXX']:
 		self.fatal('load a c++ compiler first, conf.load("compiler_cxx")')
 
-	params = {'lib': k and k[0] or kw.get('lib', None)}
+	params = {
+		'lib': k and k[0] or kw.get('lib', None),
+		'stlib': kw.get('stlib', None)
+	}
 	for key, value in self.options.__dict__.items():
 		if not key.startswith('boost_'):
 			continue
@@ -300,42 +410,53 @@
 	self.env.BOOST_VERSION = versions[0]
 	self.env.BOOST_VERSION_NUMBER = int(versions[1])
 	self.end_msg("%d.%d.%d" % (int(versions[1]) / 100000,
-				   int(versions[1]) / 100 % 1000,
-				   int(versions[1]) % 100))
+							   int(versions[1]) / 100 % 1000,
+							   int(versions[1]) % 100))
 	if Logs.verbose:
 		Logs.pprint('CYAN', '	path : %s' % self.env['INCLUDES_%s' % var])
 
-	if not params['lib']:
+	if not params['lib'] and not params['stlib']:
 		return
+	if 'static' in kw or 'static' in params:
+		Logs.warn('boost: static parameter is deprecated, use stlib instead.')
 	self.start_msg('Checking boost libs')
-	suffix = params.get('static', None) and 'ST' or ''
-	path, libs = self.boost_get_libs(**params)
-	self.env['%sLIBPATH_%s' % (suffix, var)] = [path]
-	self.env['%sLIB_%s' % (suffix, var)] = libs
+	path, libs, stlibs = self.boost_get_libs(**params)
+	self.env['LIBPATH_%s' % var] = [path]
+	self.env['STLIBPATH_%s' % var] = [path]
+	self.env['LIB_%s' % var] = libs
+	self.env['STLIB_%s' % var] = stlibs
 	self.end_msg('ok')
 	if Logs.verbose:
 		Logs.pprint('CYAN', '	path : %s' % path)
-		Logs.pprint('CYAN', '	libs : %s' % libs)
+		Logs.pprint('CYAN', '	shared libs : %s' % libs)
+		Logs.pprint('CYAN', '	static libs : %s' % stlibs)
 
+	def has_shlib(lib):
+		return params['lib'] and lib in params['lib']
+	def has_stlib(lib):
+		return params['stlib'] and lib in params['stlib']
+	def has_lib(lib):
+		return has_shlib(lib) or has_stlib(lib)
+	if has_lib('thread'):
+		# not inside try_link to make check visible in the output
+		self._check_pthread_flag(k, kw)
 
 	def try_link():
-		if 'system' in params['lib']:
-			self.check_cxx(
-			 fragment=BOOST_SYSTEM_CODE,
-			 use=var,
-			 execute=False,
-			)
-		if 'thread' in params['lib']:
-			self.check_cxx(
-			 fragment=BOOST_THREAD_CODE,
-			 use=var,
-			 execute=False,
-			)
+		if has_lib('system'):
+			self.check_cxx(fragment=BOOST_ERROR_CODE, use=var, execute=False)
+		if has_lib('thread'):
+			self.check_cxx(fragment=BOOST_THREAD_CODE, use=var, execute=False)
+		if has_lib('log'):
+			if not has_lib('thread'):
+				self.env['DEFINES_%s' % var] += ['BOOST_LOG_NO_THREADS']
+			if has_shlib('log'):
+				self.env['DEFINES_%s' % var] += ['BOOST_LOG_DYN_LINK']
+			self.check_cxx(fragment=BOOST_LOG_CODE, use=var, execute=False)
 
 	if params.get('linkage_autodetect', False):
 		self.start_msg("Attempting to detect boost linkage flags")
 		toolset = self.boost_get_toolset(kw.get('toolset', ''))
-		if toolset in ['vc']:
+		if toolset in ('vc',):
 			# disable auto-linking feature, causing error LNK1181
 			# because the code wants to be linked against
 			self.env['DEFINES_%s' % var] += ['BOOST_ALL_NO_LIB']
@@ -359,14 +480,14 @@
 				try:
 					try_link()
 					self.end_msg("ok: winning cxxflags combination: %s" % (self.env["CXXFLAGS_%s" % var]))
-					e = None
+					exc = None
 					break
-				except Errors.ConfigurationError as exc:
+				except Errors.ConfigurationError as e:
 					self.env.revert()
-					e = exc
+					exc = e
 
-			if e is not None:
-				self.end_msg("Could not auto-detect boost linking flags combination, you may report it to boost.py author", ex=e)
+			if exc is not None:
+				self.end_msg("Could not auto-detect boost linking flags combination, you may report it to boost.py author", ex=exc)
 				self.fatal('The configuration failed')
 		else:
 			self.end_msg("Boost linkage flags auto-detection not implemented (needed ?) for this toolchain")
@@ -379,3 +500,19 @@
 			self.end_msg("Could not link against boost libraries using supplied options")
 			self.fatal('The configuration failed')
 		self.end_msg('ok')
+
+
+@feature('cxx')
+@after_method('apply_link')
+def install_boost(self):
+	if install_boost.done or not Utils.is_win32 or not self.bld.cmd.startswith('install'):
+		return
+	install_boost.done = True
+	inst_to = getattr(self, 'install_path', '${BINDIR}')
+	for lib in self.env.LIB_BOOST:
+		try:
+			file = self.bld.find_file(self.env.cxxshlib_PATTERN % lib, self.env.LIBPATH_BOOST)
+			self.bld.install_files(inst_to, self.bld.root.find_node(file))
+		except:
+			continue
+install_boost.done = False
diff --git a/src/util/logger.cpp b/src/util/logger.cpp
new file mode 100644
index 0000000..04ad954
--- /dev/null
+++ b/src/util/logger.cpp
@@ -0,0 +1,113 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2016 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "logger.hpp"
+
+#include "logging.hpp"
+#include "time.hpp"
+
+#include <cinttypes>
+#include <stdio.h>
+#include <type_traits>
+
+namespace ndn {
+namespace util {
+
+std::ostream&
+operator<<(std::ostream& os, LogLevel level)
+{
+  switch (level) {
+  case LogLevel::FATAL:
+    return os << "FATAL";
+  case LogLevel::NONE:
+    return os << "NONE";
+  case LogLevel::ERROR:
+    return os << "ERROR";
+  case LogLevel::WARN:
+    return os << "WARN";
+  case LogLevel::INFO:
+    return os << "INFO";
+  case LogLevel::DEBUG:
+    return os << "DEBUG";
+  case LogLevel::TRACE:
+    return os << "TRACE";
+  case LogLevel::ALL:
+    return os << "ALL";
+  }
+
+  BOOST_THROW_EXCEPTION(std::invalid_argument("unknown log level " + to_string(static_cast<int>(level))));
+}
+
+LogLevel
+parseLogLevel(const std::string& s)
+{
+  if (s == "FATAL")
+    return LogLevel::FATAL;
+  else if (s == "NONE")
+    return LogLevel::NONE;
+  else if (s == "ERROR")
+    return LogLevel::ERROR;
+  else if (s == "WARN")
+    return LogLevel::WARN;
+  else if (s == "INFO")
+    return LogLevel::INFO;
+  else if (s == "DEBUG")
+    return LogLevel::DEBUG;
+  else if (s == "TRACE")
+    return LogLevel::TRACE;
+  else if (s == "ALL")
+    return LogLevel::ALL;
+
+  BOOST_THROW_EXCEPTION(std::invalid_argument("unrecognized log level '" + s + "'"));
+}
+
+Logger::Logger(const std::string& name)
+  : m_moduleName(name)
+{
+  this->setLevel(LogLevel::NONE);
+  Logging::addLogger(*this);
+}
+
+std::ostream&
+operator<<(std::ostream& os, const LoggerTimestamp&)
+{
+  using namespace ndn::time;
+
+  static const microseconds::rep ONE_SECOND = 1000000;
+  microseconds::rep usecs = duration_cast<microseconds>(
+                            system_clock::now().time_since_epoch()).count();
+
+  // 10 (whole seconds) + '.' + 6 (fraction) + '\0'
+  char buffer[10 + 1 + 6 + 1];
+  BOOST_ASSERT_MSG(usecs / ONE_SECOND <= 9999999999L,
+                   "whole seconds cannot fit in 10 characters");
+
+  static_assert(std::is_same<microseconds::rep, int_least64_t>::value,
+                "PRIdLEAST64 is incompatible with microseconds::rep");
+  // std::snprintf unavailable in some environments <https://redmine.named-data.net/issues/2299>
+  snprintf(buffer, sizeof(buffer), "%" PRIdLEAST64 ".%06" PRIdLEAST64,
+           usecs / ONE_SECOND, usecs % ONE_SECOND);
+
+  return os << buffer;
+}
+
+} // namespace util
+} // namespace ndn
diff --git a/src/util/logger.hpp b/src/util/logger.hpp
new file mode 100644
index 0000000..58e7b2a
--- /dev/null
+++ b/src/util/logger.hpp
@@ -0,0 +1,167 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2016 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_UTIL_LOGGER_HPP
+#define NDN_UTIL_LOGGER_HPP
+
+#include "../common.hpp"
+
+#include <boost/log/common.hpp>
+#include <boost/log/sources/logger.hpp>
+#include <atomic>
+
+namespace ndn {
+namespace util {
+
+/** \brief indicates the severity level of a log message
+ */
+enum class LogLevel {
+  FATAL   = -1,   ///< fatal (will be logged unconditionally)
+  NONE    = 0,    ///< no messages
+  ERROR   = 1,    ///< serious error messages
+  WARN    = 2,    ///< warning messages
+  INFO    = 3,    ///< informational messages
+  DEBUG   = 4,    ///< debug messages
+  TRACE   = 5,    ///< trace messages (most verbose)
+  ALL     = 255   ///< all messages
+};
+
+/** \brief output LogLevel as string
+ *  \throw std::invalid_argument unknown \p level
+ */
+std::ostream&
+operator<<(std::ostream& os, LogLevel level);
+
+/** \brief parse LogLevel from string
+ *  \throw std::invalid_argument unknown level name
+ */
+LogLevel
+parseLogLevel(const std::string& s);
+
+/** \brief represents a logger in logging facility
+ *  \note User should declare a new logger with \p NDN_CXX_LOG_INIT macro.
+ */
+class Logger : public boost::log::sources::logger_mt
+{
+public:
+  explicit
+  Logger(const std::string& name);
+
+  const std::string&
+  getModuleName() const
+  {
+    return m_moduleName;
+  }
+
+  bool
+  isLevelEnabled(LogLevel level) const
+  {
+    return m_currentLevel.load(std::memory_order_relaxed) >= level;
+  }
+
+  void
+  setLevel(LogLevel level)
+  {
+    m_currentLevel.store(level, std::memory_order_relaxed);
+  }
+
+private:
+  const std::string m_moduleName;
+  std::atomic<LogLevel> m_currentLevel;
+};
+
+/** \brief declare a log module
+ */
+#define NDN_CXX_LOG_INIT(name) \
+  namespace { \
+    inline ::ndn::util::Logger& getNdnCxxLogger() \
+    { \
+      static ::ndn::util::Logger logger(BOOST_STRINGIZE(name)); \
+      return logger; \
+    } \
+  } \
+  struct ndn_cxx__allow_trailing_semicolon
+
+/** \brief a tag that writes a timestamp upon stream output
+ *  \code
+ *  std::clog << LoggerTimestamp();
+ *  \endcode
+ */
+struct LoggerTimestamp
+{
+};
+
+/** \brief write a timestamp to \p os
+ *  \note This function is thread-safe.
+ */
+std::ostream&
+operator<<(std::ostream& os, const LoggerTimestamp&);
+
+#if (BOOST_VERSION >= 105900) && (BOOST_VERSION < 106000)
+// workaround Boost bug 11549
+#define NDN_CXX_BOOST_LOG(x) BOOST_LOG(x) << ""
+#else
+#define NDN_CXX_BOOST_LOG(x) BOOST_LOG(x)
+#endif
+
+#define NDN_CXX_LOG(lvl, lvlstr, expression) \
+  do { \
+    if (getNdnCxxLogger().isLevelEnabled(::ndn::util::LogLevel::lvl)) { \
+      NDN_CXX_BOOST_LOG(getNdnCxxLogger()) << ::ndn::util::LoggerTimestamp{} \
+        << " " BOOST_STRINGIZE(lvlstr) ": [" << getNdnCxxLogger().getModuleName() << "] " \
+        << expression; \
+    } \
+  } while (false)
+
+/** \brief log at TRACE level
+ *  \pre A log module must be declared in the same translation unit.
+ */
+#define NDN_CXX_LOG_TRACE(expression) NDN_CXX_LOG(TRACE, TRACE, expression)
+
+/** \brief log at DEBUG level
+ *  \pre A log module must be declared in the same translation unit.
+ */
+#define NDN_CXX_LOG_DEBUG(expression) NDN_CXX_LOG(DEBUG, DEBUG, expression)
+
+/** \brief log at INFO level
+ *  \pre A log module must be declared in the same translation unit.
+ */
+#define NDN_CXX_LOG_INFO(expression) NDN_CXX_LOG(INFO, INFO, expression)
+
+/** \brief log at WARN level
+ *  \pre A log module must be declared in the same translation unit.
+ */
+#define NDN_CXX_LOG_WARN(expression) NDN_CXX_LOG(WARN, WARNING, expression)
+
+/** \brief log at ERROR level
+ *  \pre A log module must be declared in the same translation unit.
+ */
+#define NDN_CXX_LOG_ERROR(expression) NDN_CXX_LOG(ERROR, ERROR, expression)
+
+/** \brief log at FATAL level
+ *  \pre A log module must be declared in the same translation unit.
+ */
+#define NDN_CXX_LOG_FATAL(expression) NDN_CXX_LOG(FATAL, FATAL, expression)
+
+} // namespace util
+} // namespace ndn
+
+#endif // NDN_UTIL_LOGGER_HPP
diff --git a/src/util/logging.cpp b/src/util/logging.cpp
new file mode 100644
index 0000000..dd10c4d
--- /dev/null
+++ b/src/util/logging.cpp
@@ -0,0 +1,209 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2016 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "logging.hpp"
+#include "logger.hpp"
+
+#include <boost/log/expressions.hpp>
+#include <cstdlib>
+#include <fstream>
+
+namespace ndn {
+namespace util {
+
+static const LogLevel INITIAL_DEFAULT_LEVEL = LogLevel::NONE;
+
+Logging&
+Logging::get()
+{
+  // Initialization of block-scope variables with static storage duration is thread-safe.
+  // See ISO C++ standard [stmt.dcl]/4
+  static Logging instance;
+  return instance;
+}
+
+Logging::Logging()
+{
+  this->setDestinationImpl(shared_ptr<std::ostream>(&std::clog, bind([]{})));
+
+  const char* environ = std::getenv("NDN_CXX_LOG");
+  if (environ != nullptr) {
+    this->setLevelImpl(environ);
+  }
+}
+
+void
+Logging::addLoggerImpl(Logger& logger)
+{
+  std::lock_guard<std::mutex> lock(m_mutex);
+
+  const std::string& moduleName = logger.getModuleName();
+  m_loggers.insert({moduleName, &logger});
+
+  auto levelIt = m_enabledLevel.find(moduleName);
+  if (levelIt == m_enabledLevel.end()) {
+    levelIt = m_enabledLevel.find("*");
+  }
+  LogLevel level = levelIt == m_enabledLevel.end() ? INITIAL_DEFAULT_LEVEL : levelIt->second;
+  logger.setLevel(level);
+}
+
+#ifdef NDN_CXX_HAVE_TESTS
+bool
+Logging::removeLogger(Logger& logger)
+{
+  const std::string& moduleName = logger.getModuleName();
+  auto range = m_loggers.equal_range(moduleName);
+  for (auto i = range.first; i != range.second; ++i) {
+    if (i->second == &logger) {
+      m_loggers.erase(i);
+      return true;
+    }
+  }
+  return false;
+}
+#endif // NDN_CXX_HAVE_TESTS
+
+void
+Logging::setLevelImpl(const std::string& moduleName, LogLevel level)
+{
+  std::lock_guard<std::mutex> lock(m_mutex);
+
+  if (moduleName == "*") {
+    this->setDefaultLevel(level);
+    return;
+  }
+
+  m_enabledLevel[moduleName] = level;
+  auto range = m_loggers.equal_range(moduleName);
+  for (auto i = range.first; i != range.second; ++i) {
+    i->second->setLevel(level);
+  }
+}
+
+void
+Logging::setDefaultLevel(LogLevel level)
+{
+  m_enabledLevel.clear();
+  m_enabledLevel["*"] = level;
+
+  for (auto i = m_loggers.begin(); i != m_loggers.end(); ++i) {
+    i->second->setLevel(level);
+  }
+}
+
+void
+Logging::setLevelImpl(const std::string& config)
+{
+  std::stringstream ss(config);
+  std::string configModule;
+  while (std::getline(ss, configModule, ':')) {
+    size_t ind = configModule.find('=');
+    if (ind == std::string::npos) {
+      BOOST_THROW_EXCEPTION(std::invalid_argument("malformed logging config: '=' is missing"));
+    }
+
+    std::string moduleName = configModule.substr(0, ind);
+    LogLevel level = parseLogLevel(configModule.substr(ind+1));
+
+    this->setLevelImpl(moduleName, level);
+  }
+}
+
+#ifdef NDN_CXX_HAVE_TESTS
+std::string
+Logging::getLevels() const
+{
+  std::ostringstream os;
+
+  auto defaultLevelIt = m_enabledLevel.find("*");
+  if (defaultLevelIt != m_enabledLevel.end()) {
+    os << "*=" << defaultLevelIt->second << ':';
+  }
+
+  for (auto it = m_enabledLevel.begin(); it != m_enabledLevel.end(); ++it) {
+    if (it->first == "*") {
+      continue;
+    }
+    os << it->first << '=' << it->second << ':';
+  }
+
+  std::string s = os.str();
+  if (!s.empty()) {
+    s.pop_back(); // delete last ':'
+  }
+  return s;
+}
+#endif // NDN_CXX_HAVE_TESTS
+
+#ifdef NDN_CXX_HAVE_TESTS
+void
+Logging::resetLevels()
+{
+  this->setDefaultLevel(INITIAL_DEFAULT_LEVEL);
+  m_enabledLevel.clear();
+}
+#endif // NDN_CXX_HAVE_TESTS
+
+void
+Logging::setDestination(std::ostream& os)
+{
+  setDestination(shared_ptr<std::ostream>(&os, bind([]{})));
+}
+
+void
+Logging::setDestinationImpl(shared_ptr<std::ostream> os)
+{
+  std::lock_guard<std::mutex> lock(m_mutex);
+
+  m_destination = os;
+
+  auto backend = boost::make_shared<boost::log::sinks::text_ostream_backend>();
+  backend->auto_flush(true);
+  backend->add_stream(boost::shared_ptr<std::ostream>(os.get(), bind([]{})));
+
+  if (m_sink != nullptr) {
+    boost::log::core::get()->remove_sink(m_sink);
+    m_sink->flush();
+    m_sink.reset();
+  }
+
+  m_sink = boost::make_shared<Sink>(backend);
+  m_sink->set_formatter(boost::log::expressions::stream << boost::log::expressions::message);
+  boost::log::core::get()->add_sink(m_sink);
+}
+
+#ifdef NDN_CXX_HAVE_TESTS
+shared_ptr<std::ostream>
+Logging::getDestination()
+{
+  return m_destination;
+}
+#endif // NDN_CXX_HAVE_TESTS
+
+void
+Logging::flushImpl()
+{
+  m_sink->flush();
+}
+
+} // namespace util
+} // namespace ndn
diff --git a/src/util/logging.hpp b/src/util/logging.hpp
new file mode 100644
index 0000000..af000c4
--- /dev/null
+++ b/src/util/logging.hpp
@@ -0,0 +1,187 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2016 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_UTIL_LOGGING_HPP
+#define NDN_UTIL_LOGGING_HPP
+
+#include "../common.hpp"
+
+#include <boost/log/sinks.hpp>
+#include <mutex>
+#include <unordered_map>
+
+namespace ndn {
+namespace util {
+
+enum class LogLevel;
+class Logger;
+
+/** \brief controls the logging facility
+ *
+ *  \note Public static methods are thread safe.
+ *        Non-public methods are not guaranteed to be thread safe.
+ */
+class Logging : noncopyable
+{
+public:
+  /** \brief register a new logger
+   *  \note App should declare a new logger with \p NDN_CXX_LOG_INIT macro.
+   */
+  static void
+  addLogger(Logger& logger);
+
+  /** \brief set severity level
+   *  \param moduleName logger name, or "*" for default level
+   *  \param level minimum severity level
+   *
+   *  Log messages are output only if its severity is greater than the set minimum severity level.
+   *  Initial default severity level is \p LogLevel::NONE which enables FATAL only.
+   *
+   *  Changing the default level overwrites individual settings.
+   */
+  static void
+  setLevel(const std::string& moduleName, LogLevel level);
+
+  /** \brief set severity levels with a config string
+   *  \param config colon-separate key=value pairs
+   *  \throw std::invalid_argument config string is malformed
+   *
+   *  \code
+   *  Logging::setSeverityLevels("*=INFO:Face=DEBUG:NfdController=WARN");
+   *  \endcode
+   *  is equivalent to
+   *  \code
+   *  Logging::setSeverityLevel("*", LogLevel::INFO);
+   *  Logging::setSeverityLevel("Face", LogLevel::DEBUG);
+   *  Logging::setSeverityLevel("NfdController", LogLevel::WARN);
+   *  \endcode
+   */
+  static void
+  setLevel(const std::string& config);
+
+  /** \brief set log destination
+   *  \param os a stream for log output
+   *
+   *  Initial destination is \p std::clog .
+   */
+  static void
+  setDestination(shared_ptr<std::ostream> os);
+
+  /** \brief set log destination
+   *  \param os a stream for log output; caller must ensure this is valid
+   *            until setDestination is invoked again or program exits
+   *
+   *  This is equivalent to setDestination(shared_ptr<std::ostream>(&os, nullDeleter))
+   */
+  static void
+  setDestination(std::ostream& os);
+
+  /** \brief flush log backend
+   *
+   *  This ensures log messages are written to the destination stream.
+   */
+  static void
+  flush();
+
+private:
+  Logging();
+
+  void
+  addLoggerImpl(Logger& logger);
+
+  void
+  setLevelImpl(const std::string& moduleName, LogLevel level);
+
+  void
+  setDefaultLevel(LogLevel level);
+
+  void
+  setLevelImpl(const std::string& config);
+
+  void
+  setDestinationImpl(shared_ptr<std::ostream> os);
+
+  void
+  flushImpl();
+
+NDN_CXX_PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+  static Logging&
+  get();
+
+#ifdef NDN_CXX_HAVE_TESTS
+  bool
+  removeLogger(Logger& logger);
+
+  std::string
+  getLevels() const;
+
+  void
+  resetLevels();
+
+  shared_ptr<std::ostream>
+  getDestination();
+#endif // NDN_CXX_HAVE_TESTS
+
+private:
+  std::mutex m_mutex;
+  std::unordered_map<std::string, LogLevel> m_enabledLevel; ///< moduleName => minimum level
+  std::unordered_multimap<std::string, Logger*> m_loggers; ///< moduleName => logger
+
+  shared_ptr<std::ostream> m_destination;
+  typedef boost::log::sinks::asynchronous_sink<boost::log::sinks::text_ostream_backend> Sink;
+  boost::shared_ptr<Sink> m_sink;
+};
+
+inline void
+Logging::addLogger(Logger& logger)
+{
+  get().addLoggerImpl(logger);
+}
+
+inline void
+Logging::setLevel(const std::string& moduleName, LogLevel level)
+{
+  get().setLevelImpl(moduleName, level);
+}
+
+inline void
+Logging::setLevel(const std::string& config)
+{
+  get().setLevelImpl(config);
+}
+
+inline void
+Logging::setDestination(shared_ptr<std::ostream> os)
+{
+  get().setDestinationImpl(os);
+}
+
+inline void
+Logging::flush()
+{
+  get().flushImpl();
+}
+
+
+} // namespace util
+} // namespace ndn
+
+#endif // NDN_UTIL_LOGGING_HPP
diff --git a/tests/unit-tests/util/log-module1.cpp b/tests/unit-tests/util/log-module1.cpp
new file mode 100644
index 0000000..dab7577
--- /dev/null
+++ b/tests/unit-tests/util/log-module1.cpp
@@ -0,0 +1,42 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2016 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+#include "util/logger.hpp"
+
+NDN_CXX_LOG_INIT(Module1);
+
+namespace ndn {
+namespace util {
+namespace tests {
+
+void
+logFromModule1()
+{
+  NDN_CXX_LOG_TRACE("trace" << 1);
+  NDN_CXX_LOG_DEBUG("debug" << 1);
+  NDN_CXX_LOG_INFO("info" << 1);
+  NDN_CXX_LOG_WARN("warn" << 1);
+  NDN_CXX_LOG_ERROR("error" << 1);
+  NDN_CXX_LOG_FATAL("fatal" << 1);
+}
+
+} // namespace tests
+} // namespace util
+} // namespace ndn
diff --git a/tests/unit-tests/util/log-module2.cpp b/tests/unit-tests/util/log-module2.cpp
new file mode 100644
index 0000000..550aa53
--- /dev/null
+++ b/tests/unit-tests/util/log-module2.cpp
@@ -0,0 +1,42 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2016 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+#include "util/logger.hpp"
+
+NDN_CXX_LOG_INIT(Module2);
+
+namespace ndn {
+namespace util {
+namespace tests {
+
+void
+logFromModule2()
+{
+  NDN_CXX_LOG_TRACE("trace" << 2);
+  NDN_CXX_LOG_DEBUG("debug" << 2);
+  NDN_CXX_LOG_INFO("info" << 2);
+  NDN_CXX_LOG_WARN("warn" << 2);
+  NDN_CXX_LOG_ERROR("error" << 2);
+  NDN_CXX_LOG_FATAL("fatal" << 2);
+}
+
+} // namespace tests
+} // namespace util
+} // namespace ndn
diff --git a/tests/unit-tests/util/logging.t.cpp b/tests/unit-tests/util/logging.t.cpp
new file mode 100644
index 0000000..da60ce1
--- /dev/null
+++ b/tests/unit-tests/util/logging.t.cpp
@@ -0,0 +1,425 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2016 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+#include "util/logging.hpp"
+#include "util/logger.hpp"
+
+#include "boost-test.hpp"
+#include <boost/test/output_test_stream.hpp>
+#include "../unit-test-time-fixture.hpp"
+
+namespace ndn {
+namespace util {
+namespace tests {
+
+using namespace ndn::tests;
+using boost::test_tools::output_test_stream;
+
+void
+logFromModule1();
+
+void
+logFromModule2();
+
+void
+logFromNewLogger(const std::string& moduleName)
+{
+  // clang complains -Wreturn-stack-address on OSX-10.9 if Logger is allocated on stack
+  auto loggerPtr = make_unique<Logger>(moduleName);
+  Logger& logger = *loggerPtr;
+
+  auto getNdnCxxLogger = [&logger] () -> Logger& { return logger; };
+  NDN_CXX_LOG_TRACE("trace" << moduleName);
+  NDN_CXX_LOG_DEBUG("debug" << moduleName);
+  NDN_CXX_LOG_INFO("info" << moduleName);
+  NDN_CXX_LOG_WARN("warn" << moduleName);
+  NDN_CXX_LOG_ERROR("error" << moduleName);
+  NDN_CXX_LOG_FATAL("fatal" << moduleName);
+
+  BOOST_CHECK(Logging::get().removeLogger(logger));
+}
+
+const time::system_clock::Duration LOG_SYSTIME = time::microseconds(1468108800311239LL);
+const std::string LOG_SYSTIME_STR = "1468108800.311239";
+
+class LoggingFixture : public UnitTestTimeFixture
+{
+protected:
+  explicit
+  LoggingFixture()
+    : m_oldLevels(Logging::get().getLevels())
+    , m_oldDestination(Logging::get().getDestination())
+  {
+    this->systemClock->setNow(LOG_SYSTIME);
+    Logging::get().resetLevels();
+    Logging::setDestination(os);
+  }
+
+  ~LoggingFixture()
+  {
+    Logging::setLevel(m_oldLevels);
+    Logging::setDestination(m_oldDestination);
+  }
+
+protected:
+  output_test_stream os;
+
+private:
+  std::string m_oldLevels;
+  shared_ptr<std::ostream> m_oldDestination;
+};
+
+BOOST_AUTO_TEST_SUITE(Util)
+BOOST_FIXTURE_TEST_SUITE(TestLogging, LoggingFixture)
+
+BOOST_AUTO_TEST_SUITE(Severity)
+
+BOOST_AUTO_TEST_CASE(None)
+{
+  Logging::setLevel("Module1", LogLevel::NONE);
+  logFromModule1();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(Error)
+{
+  Logging::setLevel("Module1", LogLevel::ERROR);
+  logFromModule1();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(Warn)
+{
+  Logging::setLevel("Module1", LogLevel::WARN);
+  logFromModule1();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(Info)
+{
+  Logging::setLevel("Module1", LogLevel::INFO);
+  logFromModule1();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " INFO: [Module1] info1\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(Debug)
+{
+  Logging::setLevel("Module1", LogLevel::DEBUG);
+  logFromModule1();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " DEBUG: [Module1] debug1\n" +
+    LOG_SYSTIME_STR + " INFO: [Module1] info1\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(Trace)
+{
+  Logging::setLevel("Module1", LogLevel::TRACE);
+  logFromModule1();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " TRACE: [Module1] trace1\n" +
+    LOG_SYSTIME_STR + " DEBUG: [Module1] debug1\n" +
+    LOG_SYSTIME_STR + " INFO: [Module1] info1\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(All)
+{
+  Logging::setLevel("Module1", LogLevel::ALL);
+  logFromModule1();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " TRACE: [Module1] trace1\n" +
+    LOG_SYSTIME_STR + " DEBUG: [Module1] debug1\n" +
+    LOG_SYSTIME_STR + " INFO: [Module1] info1\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n"
+    ));
+}
+
+BOOST_AUTO_TEST_SUITE_END() // Severity
+
+BOOST_AUTO_TEST_CASE(SameNameLoggers)
+{
+  Logging::setLevel("Module1", LogLevel::WARN);
+  logFromModule1();
+  logFromNewLogger("Module1");
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module1] warnModule1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] errorModule1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatalModule1\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(LateRegistration)
+{
+  BOOST_CHECK_NO_THROW(Logging::setLevel("Module3", LogLevel::DEBUG));
+  logFromNewLogger("Module3");
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " DEBUG: [Module3] debugModule3\n" +
+    LOG_SYSTIME_STR + " INFO: [Module3] infoModule3\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module3] warnModule3\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module3] errorModule3\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module3] fatalModule3\n"
+    ));
+}
+
+BOOST_AUTO_TEST_SUITE(DefaultSeverity)
+
+BOOST_AUTO_TEST_CASE(Unset)
+{
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(NoOverride)
+{
+  Logging::setLevel("*", LogLevel::WARN);
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module2] warn2\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module2] error2\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(Override)
+{
+  Logging::setLevel("*", LogLevel::WARN);
+  Logging::setLevel("Module2", LogLevel::DEBUG);
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " DEBUG: [Module2] debug2\n" +
+    LOG_SYSTIME_STR + " INFO: [Module2] info2\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module2] warn2\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module2] error2\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_SUITE_END() // DefaultSeverity
+
+BOOST_AUTO_TEST_SUITE(SeverityConfig)
+
+BOOST_AUTO_TEST_CASE(SetEmpty)
+{
+  Logging::setLevel("");
+  BOOST_CHECK_EQUAL(Logging::get().getLevels(), "");
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(SetDefault)
+{
+  Logging::setLevel("*=WARN");
+  BOOST_CHECK_EQUAL(Logging::get().getLevels(), "*=WARN");
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module2] warn2\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module2] error2\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(SetModule)
+{
+  Logging::setLevel("Module1=ERROR");
+  BOOST_CHECK_EQUAL(Logging::get().getLevels(), "Module1=ERROR");
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(SetOverride)
+{
+  Logging::setLevel("*=WARN:Module2=DEBUG");
+  BOOST_CHECK_EQUAL(Logging::get().getLevels(), "*=WARN:Module2=DEBUG");
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " DEBUG: [Module2] debug2\n" +
+    LOG_SYSTIME_STR + " INFO: [Module2] info2\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module2] warn2\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module2] error2\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(SetTwice)
+{
+  Logging::setLevel("*=WARN");
+  Logging::setLevel("Module2=DEBUG");
+  BOOST_CHECK_EQUAL(Logging::get().getLevels(), "*=WARN:Module2=DEBUG");
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " WARNING: [Module1] warn1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " DEBUG: [Module2] debug2\n" +
+    LOG_SYSTIME_STR + " INFO: [Module2] info2\n" +
+    LOG_SYSTIME_STR + " WARNING: [Module2] warn2\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module2] error2\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(Reset)
+{
+  Logging::setLevel("Module2=DEBUG");
+  Logging::setLevel("*=ERROR");
+  BOOST_CHECK_EQUAL(Logging::get().getLevels(), "*=ERROR");
+  logFromModule1();
+  logFromModule2();
+
+  Logging::flush();
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " ERROR: [Module1] error1\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n" +
+    LOG_SYSTIME_STR + " ERROR: [Module2] error2\n" +
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+}
+
+BOOST_AUTO_TEST_CASE(Malformed)
+{
+  BOOST_CHECK_THROW(Logging::setLevel("Module1=INVALID-LEVEL"), std::invalid_argument);
+  BOOST_CHECK_THROW(Logging::setLevel("Module1-MISSING-EQUAL-SIGN"), std::invalid_argument);
+}
+
+BOOST_AUTO_TEST_SUITE_END() // SeverityConfig
+
+BOOST_AUTO_TEST_CASE(ChangeDestination)
+{
+  logFromModule1();
+
+  auto os2 = make_shared<output_test_stream>();
+  Logging::setDestination(os2);
+  weak_ptr<output_test_stream> os2weak(os2);
+  os2.reset();
+
+  logFromModule2();
+
+  Logging::flush();
+  os2 = os2weak.lock();
+  BOOST_REQUIRE(os2 != nullptr);
+
+  BOOST_CHECK(os.is_equal(
+    LOG_SYSTIME_STR + " FATAL: [Module1] fatal1\n"
+    ));
+  BOOST_CHECK(os2->is_equal(
+    LOG_SYSTIME_STR + " FATAL: [Module2] fatal2\n"
+    ));
+
+  os2.reset();
+  Logging::setDestination(os);
+  BOOST_CHECK(os2weak.expired());
+}
+
+BOOST_AUTO_TEST_SUITE_END() // TestLogging
+BOOST_AUTO_TEST_SUITE_END() // Util
+
+} // namespace tests
+} // namespace util
+} // namespace ndn
diff --git a/wscript b/wscript
index 1b0b002..76c39a8 100644
--- a/wscript
+++ b/wscript
@@ -101,12 +101,14 @@
     conf.check_openssl(mandatory=True, atleast_version=0x10001000) # 1.0.1
 
     USED_BOOST_LIBS = ['system', 'filesystem', 'date_time', 'iostreams',
-                       'regex', 'program_options', 'chrono', 'random']
+                       'regex', 'program_options', 'chrono', 'random',
+                       'thread', 'log', 'log_setup']
+
     if conf.env['WITH_TESTS']:
         USED_BOOST_LIBS += ['unit_test_framework']
         conf.define('HAVE_TESTS', 1)
 
-    conf.check_boost(lib=USED_BOOST_LIBS, mandatory=True)
+    conf.check_boost(lib=USED_BOOST_LIBS, mandatory=True, mt=True)
     if conf.env.BOOST_VERSION_NUMBER < 105400:
         Logs.error("Minimum required boost version is 1.54.0")
         Logs.error("Please upgrade your distribution or install custom boost libraries" +