Skip to content
Snippets Groups Projects
loguru.cpp 51 KiB
Newer Older
Nicolas Pope's avatar
Nicolas Pope committed
// Disable all warnings from gcc/clang:
#ifdef __GNUC__
Nicolas Pope's avatar
Nicolas Pope committed
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas"

#pragma GCC diagnostic ignored "-Wc++98-compat"
#pragma GCC diagnostic ignored "-Wc++98-compat-pedantic"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#pragma GCC diagnostic ignored "-Wmissing-prototypes"
#pragma GCC diagnostic ignored "-Wpadded"
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma GCC diagnostic ignored "-Wunused-macros"
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif  // __GNUC__
Nicolas Pope's avatar
Nicolas Pope committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

#define LOGURU_REPLACE_GLOG 1
#include "loguru.hpp"

#ifndef LOGURU_HAS_BEEN_IMPLEMENTED
#define LOGURU_HAS_BEEN_IMPLEMENTED

#define LOGURU_PREAMBLE_WIDTH (53 + LOGURU_THREADNAME_WIDTH + LOGURU_FILENAME_WIDTH)

#undef min
#undef max

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <regex>
#include <string>
#include <thread>
#include <vector>

#ifdef _WIN32
	#include <direct.h>

	#define localtime_r(a, b) localtime_s(b, a) // No localtime_r with MSVC, but arguments are swapped for localtime_s
#else
	#include <signal.h>
	#include <sys/stat.h> // mkdir
	#include <unistd.h>   // STDERR_FILENO
#endif

#ifdef __linux__
	#include <linux/limits.h> // PATH_MAX
#elif !defined(_WIN32)
	#include <limits.h> // PATH_MAX
#endif

#ifndef PATH_MAX
	#define PATH_MAX 1024
#endif

#ifdef __APPLE__
	#include "TargetConditionals.h"
#endif

// TODO: use defined(_POSIX_VERSION) for some of these things?

#if defined(_WIN32) || defined(__CYGWIN__)
	#define LOGURU_PTHREADS    0
	#define LOGURU_WINTHREADS  1
	#ifndef LOGURU_STACKTRACES
		#define LOGURU_STACKTRACES 0
	#endif
#elif defined(__rtems__)
	#define LOGURU_PTHREADS    1
	#define LOGURU_WINTHREADS  0
	#ifndef LOGURU_STACKTRACES
		#define LOGURU_STACKTRACES 0
	#endif
#else
	#define LOGURU_PTHREADS    1
	#define LOGURU_WINTHREADS  0
	#ifndef LOGURU_STACKTRACES
		#define LOGURU_STACKTRACES 1
	#endif
#endif

#if LOGURU_STACKTRACES
	#include <cxxabi.h>    // for __cxa_demangle
	#include <dlfcn.h>     // for dladdr
	#include <execinfo.h>  // for backtrace
#endif // LOGURU_STACKTRACES

#if LOGURU_PTHREADS
	#include <pthread.h>
	#if defined(__FreeBSD__)
		#include <pthread_np.h>
		#include <sys/thr.h>
	#elif defined(__OpenBSD__)
		#include <pthread_np.h>
	#endif

	#ifdef __linux__
		/* On Linux, the default thread name is the same as the name of the binary.
		   Additionally, all new threads inherit the name of the thread it got forked from.
		   For this reason, Loguru use the pthread Thread Local Storage
		   for storing thread names on Linux. */
		#define LOGURU_PTLS_NAMES 1
	#endif
#endif

#if LOGURU_WINTHREADS
	#ifndef _WIN32_WINNT
		#define _WIN32_WINNT 0x0502
	#endif
	#define WIN32_LEAN_AND_MEAN
	#define NOMINMAX
	#include <windows.h>
#endif

#ifndef LOGURU_PTLS_NAMES
   #define LOGURU_PTLS_NAMES 0
#endif

namespace loguru
{
	using namespace std::chrono;

#if LOGURU_WITH_FILEABS
	struct FileAbs
	{
		char path[PATH_MAX];
		char mode_str[4];
		Verbosity verbosity;
		struct stat st;
		FILE* fp;
		bool is_reopening = false; // to prevent recursive call in file_reopen.
		decltype(steady_clock::now()) last_check_time = steady_clock::now();
	};
#else
	typedef FILE* FileAbs;
#endif

	struct Callback
	{
		std::string     id;
		log_handler_t   callback;
		void*           user_data;
		Verbosity       verbosity; // Does not change!
		close_handler_t close;
		flush_handler_t flush;
		unsigned        indentation;
	};

	using CallbackVec = std::vector<Callback>;

	using StringPair     = std::pair<std::string, std::string>;
	using StringPairList = std::vector<StringPair>;

	const auto s_start_time = steady_clock::now();

	Verbosity g_stderr_verbosity  = Verbosity_0;
	bool      g_colorlogtostderr  = true;
	unsigned  g_flush_interval_ms = 0;
	bool      g_preamble          = true;

	// Preamble details
	bool      g_preamble_date     = true;
	bool      g_preamble_time     = true;
	bool      g_preamble_uptime   = true;
	bool      g_preamble_thread   = true;
	bool      g_preamble_file     = true;
	bool      g_preamble_verbose  = true;
	bool      g_preamble_pipe     = true;

	static std::recursive_mutex  s_mutex;
	static Verbosity             s_max_out_verbosity = Verbosity_OFF;
	static std::string           s_argv0_filename;
	static std::string           s_arguments;
	static char                  s_current_dir[PATH_MAX];
	static CallbackVec           s_callbacks;
	static fatal_handler_t       s_fatal_handler   = nullptr;
	static verbosity_to_name_t   s_verbosity_to_name_callback = nullptr;
	static name_to_verbosity_t   s_name_to_verbosity_callback = nullptr;
	static StringPairList        s_user_stack_cleanups;
	static bool                  s_strip_file_path = true;
	static std::atomic<unsigned> s_stderr_indentation { 0 };

	// For periodic flushing:
	static std::thread* s_flush_thread   = nullptr;
	static bool         s_needs_flushing = false;

	static const bool s_terminal_has_color = [](){
		#ifdef _WIN32
			#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
			#define ENABLE_VIRTUAL_TERMINAL_PROCESSING  0x0004
			#endif

			HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
			if (hOut != INVALID_HANDLE_VALUE) {
				DWORD dwMode = 0;
				GetConsoleMode(hOut, &dwMode);
				dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
				return SetConsoleMode(hOut, dwMode) != 0;
			}
			return false;
		#else
			if (const char* term = getenv("TERM")) {
				return 0 == strcmp(term, "cygwin")
					|| 0 == strcmp(term, "linux")
					|| 0 == strcmp(term, "rxvt-unicode-256color")
					|| 0 == strcmp(term, "screen")
					|| 0 == strcmp(term, "screen-256color")
					|| 0 == strcmp(term, "tmux-256color")
					|| 0 == strcmp(term, "xterm")
					|| 0 == strcmp(term, "xterm-256color")
					|| 0 == strcmp(term, "xterm-termite")
					|| 0 == strcmp(term, "xterm-color");
			} else {
				return false;
			}
		#endif
	}();

	static void print_preamble_header(char* out_buff, size_t out_buff_size);

	#if LOGURU_PTLS_NAMES
		static pthread_once_t s_pthread_key_once = PTHREAD_ONCE_INIT;
		static pthread_key_t  s_pthread_key_name;

		void make_pthread_key_name()
		{
			(void)pthread_key_create(&s_pthread_key_name, free);
		}
	#endif

	// ------------------------------------------------------------------------------
	// Colors

	bool terminal_has_color() { return s_terminal_has_color; }

	// Colors

#ifdef _WIN32
#define VTSEQ(ID) ("\x1b[1;" #ID "m")
#else
#define VTSEQ(ID) ("\x1b[" #ID "m")
#endif

	const char* terminal_black()      { return s_terminal_has_color ? VTSEQ(30) : ""; }
	const char* terminal_red()        { return s_terminal_has_color ? VTSEQ(31) : ""; }
	const char* terminal_green()      { return s_terminal_has_color ? VTSEQ(32) : ""; }
	const char* terminal_yellow()     { return s_terminal_has_color ? VTSEQ(33) : ""; }
	const char* terminal_blue()       { return s_terminal_has_color ? VTSEQ(34) : ""; }
	const char* terminal_purple()     { return s_terminal_has_color ? VTSEQ(35) : ""; }
	const char* terminal_cyan()       { return s_terminal_has_color ? VTSEQ(36) : ""; }
	const char* terminal_light_gray() { return s_terminal_has_color ? VTSEQ(37) : ""; }
	const char* terminal_white()      { return s_terminal_has_color ? VTSEQ(37) : ""; }
	const char* terminal_light_red()  { return s_terminal_has_color ? VTSEQ(91) : ""; }
	const char* terminal_dim()        { return s_terminal_has_color ? VTSEQ(2)  : ""; }

	// Formating
	const char* terminal_bold()       { return s_terminal_has_color ? VTSEQ(1) : ""; }
	const char* terminal_underline()  { return s_terminal_has_color ? VTSEQ(4) : ""; }

	// You should end each line with this!
	const char* terminal_reset()      { return s_terminal_has_color ? VTSEQ(0) : ""; }

	// ------------------------------------------------------------------------------
#if LOGURU_WITH_FILEABS
	void file_reopen(void* user_data);
	inline FILE* to_file(void* user_data) { return reinterpret_cast<FileAbs*>(user_data)->fp; }
#else
	inline FILE* to_file(void* user_data) { return reinterpret_cast<FILE*>(user_data); }
#endif

	void file_log(void* user_data, const Message& message)
	{
#if LOGURU_WITH_FILEABS
		FileAbs* file_abs = reinterpret_cast<FileAbs*>(user_data);
		if (file_abs->is_reopening) {
			return;
		}
		// It is better checking file change every minute/hour/day,
		// instead of doing this every time we log.
		// Here check_interval is set to zero to enable checking every time;
		const auto check_interval = seconds(0);
		if (duration_cast<seconds>(steady_clock::now() - file_abs->last_check_time) > check_interval) {
			file_abs->last_check_time = steady_clock::now();
			file_reopen(user_data);
		}
		FILE* file = to_file(user_data);
		if (!file) {
			return;
		}
#else
		FILE* file = to_file(user_data);
#endif
		fprintf(file, "%s%s%s%s\n",
			message.preamble, message.indentation, message.prefix, message.message);
		if (g_flush_interval_ms == 0) {
			fflush(file);
		}
	}

	void file_close(void* user_data)
	{
		FILE* file = to_file(user_data);
		if (file) {
			fclose(file);
		}
#if LOGURU_WITH_FILEABS
		delete reinterpret_cast<FileAbs*>(user_data);
#endif
	}

	void file_flush(void* user_data)
	{
		FILE* file = to_file(user_data);
		fflush(file);
	}

#if LOGURU_WITH_FILEABS
	void file_reopen(void* user_data)
	{
		FileAbs * file_abs = reinterpret_cast<FileAbs*>(user_data);
		struct stat st;
		int ret;
		if (!file_abs->fp || (ret = stat(file_abs->path, &st)) == -1 || (st.st_ino != file_abs->st.st_ino)) {
			file_abs->is_reopening = true;
			if (file_abs->fp) {
				fclose(file_abs->fp);
			}
			if (!file_abs->fp) {
				LOG_F(INFO, "Reopening file '%s' due to previous error", file_abs->path);
			}
			else if (ret < 0) {
				const auto why = errno_as_text();
				LOG_F(INFO, "Reopening file '%s' due to '%s'", file_abs->path, why.c_str());
			} else {
				LOG_F(INFO, "Reopening file '%s' due to file changed", file_abs->path);
			}
			// try reopen current file.
			if (!create_directories(file_abs->path)) {
				LOG_F(ERROR, "Failed to create directories to '%s'", file_abs->path);
			}
			file_abs->fp = fopen(file_abs->path, file_abs->mode_str);
			if (!file_abs->fp) {
				LOG_F(ERROR, "Failed to open '%s'", file_abs->path);
			} else {
				stat(file_abs->path, &file_abs->st);
			}
			file_abs->is_reopening = false;
		}
	}
#endif
	// ------------------------------------------------------------------------------

	// Helpers:

	Text::~Text() { free(_str); }

	LOGURU_PRINTF_LIKE(1, 0)
	static Text vtextprintf(const char* format, va_list vlist)
	{
#ifdef _WIN32
		int bytes_needed = _vscprintf(format, vlist);
		CHECK_F(bytes_needed >= 0, "Bad string format: '%s'", format);
		char* buff = (char*)malloc(bytes_needed+1);
		vsnprintf(buff, bytes_needed+1, format, vlist);
		return Text(buff);
#else
		char* buff = nullptr;
		int result = vasprintf(&buff, format, vlist);
		CHECK_F(result >= 0, "Bad string format: '%s'", format);
		return Text(buff);
#endif
	}

	Text textprintf(const char* format, ...)
	{
		va_list vlist;
		va_start(vlist, format);
		auto result = vtextprintf(format, vlist);
		va_end(vlist);
		return result;
	}

	// Overloaded for variadic template matching.
	Text textprintf()
	{
		return Text(static_cast<char*>(calloc(1, 1)));
	}

	static const char* indentation(unsigned depth)
	{
		static const char buff[] =
		".   .   .   .   .   .   .   .   .   .   " ".   .   .   .   .   .   .   .   .   .   "
		".   .   .   .   .   .   .   .   .   .   " ".   .   .   .   .   .   .   .   .   .   "
		".   .   .   .   .   .   .   .   .   .   " ".   .   .   .   .   .   .   .   .   .   "
		".   .   .   .   .   .   .   .   .   .   " ".   .   .   .   .   .   .   .   .   .   "
		".   .   .   .   .   .   .   .   .   .   " ".   .   .   .   .   .   .   .   .   .   ";
		static const size_t INDENTATION_WIDTH = 4;
		static const size_t NUM_INDENTATIONS = (sizeof(buff) - 1) / INDENTATION_WIDTH;
		depth = std::min<unsigned>(depth, NUM_INDENTATIONS);
		return buff + INDENTATION_WIDTH * (NUM_INDENTATIONS - depth);
	}

	static void parse_args(int& argc, char* argv[], const char* verbosity_flag)
	{
		int arg_dest = 1;
		int out_argc = argc;

		for (int arg_it = 1; arg_it < argc; ++arg_it) {
			auto cmd = argv[arg_it];
			auto arg_len = strlen(verbosity_flag);
			if (strncmp(cmd, verbosity_flag, arg_len) == 0 && !std::isalpha(cmd[arg_len], std::locale(""))) {
				out_argc -= 1;
				auto value_str = cmd + arg_len;
				if (value_str[0] == '\0') {
					// Value in separate argument
					arg_it += 1;
					CHECK_LT_F(arg_it, argc, "Missing verbosiy level after %s", verbosity_flag);
					value_str = argv[arg_it];
					out_argc -= 1;
				}
				if (*value_str == '=') { value_str += 1; }

				auto req_verbosity = get_verbosity_from_name(value_str);
				if (req_verbosity != Verbosity_INVALID) {
					g_stderr_verbosity = req_verbosity;
				} else {
					char* end = 0;
					g_stderr_verbosity = static_cast<int>(strtol(value_str, &end, 10));
					CHECK_F(end && *end == '\0',
						"Invalid verbosity. Expected integer, INFO, WARNING, ERROR or OFF, got '%s'", value_str);
				}
			} else {
				argv[arg_dest++] = argv[arg_it];
			}
		}

		argc = out_argc;
		argv[argc] = nullptr;
	}

	static long long now_ns()
	{
		return duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch()).count();
	}

	// Returns the part of the path after the last / or \ (if any).
	const char* filename(const char* path)
	{
		for (auto ptr = path; *ptr; ++ptr) {
			if (*ptr == '/' || *ptr == '\\') {
				path = ptr + 1;
			}
		}
		return path;
	}

	// ------------------------------------------------------------------------------

	static void on_atexit()
	{
		LOG_F(INFO, "atexit");
		flush();
	}

	static void install_signal_handlers();

	static void write_hex_digit(std::string& out, unsigned num)
	{
		DCHECK_LT_F(num, 16u);
		if (num < 10u) { out.push_back(char('0' + num)); }
		else { out.push_back(char('A' + num - 10)); }
	}

	static void write_hex_byte(std::string& out, uint8_t n)
	{
		write_hex_digit(out, n >> 4u);
		write_hex_digit(out, n & 0x0f);
	}

	static void escape(std::string& out, const std::string& str)
	{
		for (char c : str) {
			/**/ if (c == '\a') { out += "\\a";  }
			else if (c == '\b') { out += "\\b";  }
			else if (c == '\f') { out += "\\f";  }
			else if (c == '\n') { out += "\\n";  }
			else if (c == '\r') { out += "\\r";  }
			else if (c == '\t') { out += "\\t";  }
			else if (c == '\v') { out += "\\v";  }
			else if (c == '\\') { out += "\\\\"; }
			else if (c == '\'') { out += "\\\'"; }
			else if (c == '\"') { out += "\\\""; }
			else if (c == ' ')  { out += "\\ ";  }
			else if (0 <= c && c < 0x20) { // ASCI control character:
			// else if (c < 0x20 || c != (c & 127)) { // ASCII control character or UTF-8:
				out += "\\x";
				write_hex_byte(out, static_cast<uint8_t>(c));
			} else { out += c; }
		}
	}

	Text errno_as_text()
	{
		// cppcheck-suppress unusedVariable
Nicolas Pope's avatar
Nicolas Pope committed
		char buff[256];
	#if defined(__GLIBC__) && defined(_GNU_SOURCE)
		// GNU Version
		return Text(strdup(strerror_r(errno, buff, sizeof(buff))));
	#elif defined(__APPLE__) || _POSIX_C_SOURCE >= 200112L
		// XSI Version
		strerror_r(errno, buff, sizeof(buff));
		return Text(strdup(buff));
	#elif defined(_WIN32)
		strerror_s(buff, sizeof(buff), errno);
		return Text(strdup(buff));
	#else
		// Not thread-safe.
		return Text(strdup(strerror(errno)));
	#endif
	}

	void init(int& argc, char* argv[], const char* verbosity_flag)
	{
		CHECK_GT_F(argc,       0,       "Expected proper argc/argv");
		CHECK_EQ_F(argv[argc], nullptr, "Expected proper argc/argv");

		// Nick: Added to allow for multiple calls to init during tests
		if (s_argv0_filename.size() > 0) return;

Nicolas Pope's avatar
Nicolas Pope committed
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
		s_argv0_filename = filename(argv[0]);

		#ifdef _WIN32
			#define getcwd _getcwd
		#endif

		if (!getcwd(s_current_dir, sizeof(s_current_dir)))
		{
			const auto error_text = errno_as_text();
			LOG_F(WARNING, "Failed to get current working directory: %s", error_text.c_str());
		}

		s_arguments = "";
		for (int i = 0; i < argc; ++i) {
			escape(s_arguments, argv[i]);
			if (i + 1 < argc) {
				s_arguments += " ";
			}
		}

		if (verbosity_flag) {
			parse_args(argc, argv, verbosity_flag);
		}

		#if LOGURU_PTLS_NAMES || LOGURU_WINTHREADS
			set_thread_name("main thread");
		#elif LOGURU_PTHREADS
			char old_thread_name[16] = {0};
			auto this_thread = pthread_self();
			#if defined(__APPLE__) || defined(__linux__)
				pthread_getname_np(this_thread, old_thread_name, sizeof(old_thread_name));
			#endif
			if (old_thread_name[0] == 0) {
				#ifdef __APPLE__
					pthread_setname_np("main thread");
				#elif defined(__FreeBSD__) || defined(__OpenBSD__)
					pthread_set_name_np(this_thread, "main thread");
				#elif defined(__linux__)
					pthread_setname_np(this_thread, "main thread");
				#endif
			}
		#endif // LOGURU_PTHREADS

		if (g_stderr_verbosity >= Verbosity_INFO) {
			if (g_preamble) {
				char preamble_explain[LOGURU_PREAMBLE_WIDTH];
				print_preamble_header(preamble_explain, sizeof(preamble_explain));
				if (g_colorlogtostderr && s_terminal_has_color) {
					fprintf(stderr, "%s%s%s\n", terminal_reset(), terminal_dim(), preamble_explain);
				} else {
					fprintf(stderr, "%s\n", preamble_explain);
				}
			}
			fflush(stderr);
		}
		LOG_F(INFO, "arguments: %s", s_arguments.c_str());
		if (strlen(s_current_dir) != 0)
		{
			LOG_F(INFO, "Current dir: %s", s_current_dir);
		}
		LOG_F(INFO, "stderr verbosity: %d", g_stderr_verbosity);
		LOG_F(INFO, "-----------------------------------");

		install_signal_handlers();

		atexit(on_atexit);
	}

	void shutdown()
	{
		LOG_F(INFO, "loguru::shutdown()");
		remove_all_callbacks();
		set_fatal_handler(nullptr);
		set_verbosity_to_name_callback(nullptr);
		set_name_to_verbosity_callback(nullptr);
	}

	void write_date_time(char* buff, size_t buff_size)
	{
		auto now = system_clock::now();
		long long ms_since_epoch = duration_cast<milliseconds>(now.time_since_epoch()).count();
		time_t sec_since_epoch = time_t(ms_since_epoch / 1000);
		tm time_info;
		localtime_r(&sec_since_epoch, &time_info);
		snprintf(buff, buff_size, "%04d%02d%02d_%02d%02d%02d.%03lld",
			1900 + time_info.tm_year, 1 + time_info.tm_mon, time_info.tm_mday,
			time_info.tm_hour, time_info.tm_min, time_info.tm_sec, ms_since_epoch % 1000);
	}

	const char* argv0_filename()
	{
		return s_argv0_filename.c_str();
	}

	const char* arguments()
	{
		return s_arguments.c_str();
	}

	const char* current_dir()
	{
		return s_current_dir;
	}

	const char* home_dir()
	{
		#ifdef _WIN32
			auto user_profile = getenv("USERPROFILE");
			CHECK_F(user_profile != nullptr, "Missing USERPROFILE");
			return user_profile;
		#else // _WIN32
			auto home = getenv("HOME");
			CHECK_F(home != nullptr, "Missing HOME");
			return home;
		#endif // _WIN32
	}

	void suggest_log_path(const char* prefix, char* buff, unsigned buff_size)
	{
		if (prefix[0] == '~') {
			snprintf(buff, buff_size - 1, "%s%s", home_dir(), prefix + 1);
		} else {
			snprintf(buff, buff_size - 1, "%s", prefix);
		}

		// Check for terminating /
		size_t n = strlen(buff);
		if (n != 0) {
			if (buff[n - 1] != '/') {
				CHECK_F(n + 2 < buff_size, "Filename buffer too small");
				buff[n] = '/';
				buff[n + 1] = '\0';
			}
		}

		strncat(buff, s_argv0_filename.c_str(), buff_size - strlen(buff) - 1);
		strncat(buff, "/",                      buff_size - strlen(buff) - 1);
		write_date_time(buff + strlen(buff),    buff_size - strlen(buff));
		strncat(buff, ".log",                   buff_size - strlen(buff) - 1);
	}

	bool create_directories(const char* file_path_const)
	{
		CHECK_F(file_path_const && *file_path_const);
		char* file_path = strdup(file_path_const);
		for (char* p = strchr(file_path + 1, '/'); p; p = strchr(p + 1, '/')) {
			*p = '\0';

	#ifdef _WIN32
			if (_mkdir(file_path) == -1) {
	#else
			if (mkdir(file_path, 0755) == -1) {
	#endif
				if (errno != EEXIST) {
					LOG_F(ERROR, "Failed to create directory '%s'", file_path);
					LOG_IF_F(ERROR, errno == EACCES,       "EACCES");
					LOG_IF_F(ERROR, errno == ENAMETOOLONG, "ENAMETOOLONG");
					LOG_IF_F(ERROR, errno == ENOENT,       "ENOENT");
					LOG_IF_F(ERROR, errno == ENOTDIR,      "ENOTDIR");
					LOG_IF_F(ERROR, errno == ELOOP,        "ELOOP");

					*p = '/';
					free(file_path);
					return false;
				}
			}
			*p = '/';
		}
		free(file_path);
		return true;
	}
	bool add_file(const char* path_in, FileMode mode, Verbosity verbosity)
	{
		char path[PATH_MAX];
		if (path_in[0] == '~') {
			snprintf(path, sizeof(path) - 1, "%s%s", home_dir(), path_in + 1);
		} else {
			snprintf(path, sizeof(path) - 1, "%s", path_in);
		}

		if (!create_directories(path)) {
			LOG_F(ERROR, "Failed to create directories to '%s'", path);
		}

		const char* mode_str = (mode == FileMode::Truncate ? "w" : "a");
		auto file = fopen(path, mode_str);
		if (!file) {
			LOG_F(ERROR, "Failed to open '%s'", path);
			return false;
		}
#if LOGURU_WITH_FILEABS
		FileAbs* file_abs = new FileAbs(); // this is deleted in file_close;
		snprintf(file_abs->path, sizeof(file_abs->path) - 1, "%s", path);
		snprintf(file_abs->mode_str, sizeof(file_abs->mode_str) - 1, "%s", mode_str);
		stat(file_abs->path, &file_abs->st);
		file_abs->fp = file;
		file_abs->verbosity = verbosity;
		add_callback(path_in, file_log, file_abs, verbosity, file_close, file_flush);
#else
		add_callback(path_in, file_log, file, verbosity, file_close, file_flush);
#endif

		if (mode == FileMode::Append) {
			fprintf(file, "\n\n\n\n\n");
		}
		if (!s_arguments.empty()) {
			fprintf(file, "arguments: %s\n", s_arguments.c_str());
		}
		if (strlen(s_current_dir) != 0) {
			fprintf(file, "Current dir: %s\n", s_current_dir);
		}
		fprintf(file, "File verbosity level: %d\n", verbosity);
		if (g_preamble) {
			char preamble_explain[LOGURU_PREAMBLE_WIDTH];
			print_preamble_header(preamble_explain, sizeof(preamble_explain));
			fprintf(file, "%s\n", preamble_explain);
		}
		fflush(file);

		LOG_F(INFO, "Logging to '%s', mode: '%s', verbosity: %d", path, mode_str, verbosity);
		return true;
	}

	// Will be called right before abort().
	void set_fatal_handler(fatal_handler_t handler)
	{
		s_fatal_handler = handler;
	}

	fatal_handler_t get_fatal_handler()
	{
		return s_fatal_handler;
	}

	void set_verbosity_to_name_callback(verbosity_to_name_t callback)
	{
		s_verbosity_to_name_callback = callback;
	}

	void set_name_to_verbosity_callback(name_to_verbosity_t callback)
	{
		s_name_to_verbosity_callback = callback;
	}

	void add_stack_cleanup(const char* find_this, const char* replace_with_this)
	{
		if (strlen(find_this) <= strlen(replace_with_this)) {
			LOG_F(WARNING, "add_stack_cleanup: the replacement should be shorter than the pattern!");
			return;
		}

		s_user_stack_cleanups.push_back(StringPair(find_this, replace_with_this));
	}

	static void on_callback_change()
	{
		s_max_out_verbosity = Verbosity_OFF;
		for (const auto& callback : s_callbacks) {
			s_max_out_verbosity = std::max(s_max_out_verbosity, callback.verbosity);
		}
	}

	void add_callback(
		const char*     id,
		log_handler_t   callback,
		void*           user_data,
		Verbosity       verbosity,
		close_handler_t on_close,
		flush_handler_t on_flush)
	{
		std::lock_guard<std::recursive_mutex> lock(s_mutex);
		s_callbacks.push_back(Callback{id, callback, user_data, verbosity, on_close, on_flush, 0});
		on_callback_change();
	}

	// Returns a custom verbosity name if one is available, or nullptr.
	// See also set_verbosity_to_name_callback.
	const char* get_verbosity_name(Verbosity verbosity)
	{
		auto name = s_verbosity_to_name_callback
				? (*s_verbosity_to_name_callback)(verbosity)
				: nullptr;

		// Use standard replacements if callback fails:
		if (!name)
		{
			if (verbosity <= Verbosity_FATAL) {
				name = "FATL";
			} else if (verbosity == Verbosity_ERROR) {
				name = "ERR";
			} else if (verbosity == Verbosity_WARNING) {
				name = "WARN";
			} else if (verbosity == Verbosity_INFO) {
				name = "INFO";
			}
		}

		return name;
	}

	// Returns Verbosity_INVALID if the name is not found.
	// See also set_name_to_verbosity_callback.
	Verbosity get_verbosity_from_name(const char* name)
	{
		auto verbosity = s_name_to_verbosity_callback
				? (*s_name_to_verbosity_callback)(name)
				: Verbosity_INVALID;

		// Use standard replacements if callback fails:
		if (verbosity == Verbosity_INVALID) {
			if (strcmp(name, "OFF") == 0) {
				verbosity = Verbosity_OFF;
			} else if (strcmp(name, "INFO") == 0) {
				verbosity = Verbosity_INFO;
			} else if (strcmp(name, "WARNING") == 0) {
				verbosity = Verbosity_WARNING;
			} else if (strcmp(name, "ERROR") == 0) {
				verbosity = Verbosity_ERROR;
			} else if (strcmp(name, "FATAL") == 0) {
				verbosity = Verbosity_FATAL;
			}
		}

		return verbosity;
	}

	bool remove_callback(const char* id)
	{
		std::lock_guard<std::recursive_mutex> lock(s_mutex);
		auto it = std::find_if(begin(s_callbacks), end(s_callbacks), [&](const Callback& c) { return c.id == id; });
		if (it != s_callbacks.end()) {
			if (it->close) { it->close(it->user_data); }
			s_callbacks.erase(it);
			on_callback_change();
			return true;
		} else {
			LOG_F(ERROR, "Failed to locate callback with id '%s'", id);
			return false;
		}
	}

	void remove_all_callbacks()
	{
		std::lock_guard<std::recursive_mutex> lock(s_mutex);
		for (auto& callback : s_callbacks) {
			if (callback.close) {
				callback.close(callback.user_data);
			}
		}
		s_callbacks.clear();
		on_callback_change();
	}

	// Returns the maximum of g_stderr_verbosity and all file/custom outputs.
	Verbosity current_verbosity_cutoff()
	{
		return g_stderr_verbosity > s_max_out_verbosity ?
			   g_stderr_verbosity : s_max_out_verbosity;
	}

#if LOGURU_WINTHREADS
	char* get_thread_name_win32()
	{
		__declspec( thread ) static char thread_name[LOGURU_THREADNAME_WIDTH + 1] = {0};
		return &thread_name[0];
	}
#endif // LOGURU_WINTHREADS

	void set_thread_name(const char* name)
	{
		#if LOGURU_PTLS_NAMES
			(void)pthread_once(&s_pthread_key_once, make_pthread_key_name);
			(void)pthread_setspecific(s_pthread_key_name, strdup(name));

		#elif LOGURU_PTHREADS
			#ifdef __APPLE__
				pthread_setname_np(name);
			#elif defined(__FreeBSD__) || defined(__OpenBSD__)
				pthread_set_name_np(pthread_self(), name);
			#elif defined(__linux__)
				pthread_setname_np(pthread_self(), name);
			#endif
		#elif LOGURU_WINTHREADS
			strncpy_s(get_thread_name_win32(), LOGURU_THREADNAME_WIDTH + 1, name, _TRUNCATE);
		#else // LOGURU_PTHREADS
			(void)name;
		#endif // LOGURU_PTHREADS
	}

#if LOGURU_PTLS_NAMES
	const char* get_thread_name_ptls()
	{
		(void)pthread_once(&s_pthread_key_once, make_pthread_key_name);
		return static_cast<const char*>(pthread_getspecific(s_pthread_key_name));
	}
#endif // LOGURU_PTLS_NAMES

	void get_thread_name(char* buffer, unsigned long long length, bool right_align_hext_id)
	{
		CHECK_NE_F(length, 0u, "Zero length buffer in get_thread_name");
		CHECK_NOTNULL_F(buffer, "nullptr in get_thread_name");
#if LOGURU_PTHREADS
		auto thread = pthread_self();
		#if LOGURU_PTLS_NAMES
			if (const char* name = get_thread_name_ptls()) {
				snprintf(buffer, length, "%s", name);
			} else {
				buffer[0] = 0;
			}
		#elif defined(__APPLE__) || defined(__linux__)
			pthread_getname_np(thread, buffer, length);
		#else
			buffer[0] = 0;
		#endif

		if (buffer[0] == 0) {
			#ifdef __APPLE__
				uint64_t thread_id;
				pthread_threadid_np(thread, &thread_id);
			#elif defined(__FreeBSD__)
				long thread_id;
				(void)thr_self(&thread_id);
			#elif defined(__OpenBSD__)
				unsigned thread_id = -1;
			#else
				uint64_t thread_id = thread;
			#endif
			if (right_align_hext_id) {
				snprintf(buffer, length, "%*X", static_cast<int>(length - 1), static_cast<unsigned>(thread_id));
			} else {
				snprintf(buffer, length, "%X", static_cast<unsigned>(thread_id));
			}
		}
#elif LOGURU_WINTHREADS
		if (const char* name = get_thread_name_win32()) {
			snprintf(buffer, (size_t)length, "%s", name);
		} else {
			buffer[0] = 0;
		}
#else // !LOGURU_WINTHREADS && !LOGURU_WINTHREADS
		buffer[0] = 0;
#endif

	}

	// ------------------------------------------------------------------------
	// Stack traces

#if LOGURU_STACKTRACES
	Text demangle(const char* name)
	{
		int status = -1;
		char* demangled = abi::__cxa_demangle(name, 0, 0, &status);
		Text result{status == 0 ? demangled : strdup(name)};
		return result;
	}

	#if LOGURU_RTTI
		template <class T>
		std::string type_name()
		{
			auto demangled = demangle(typeid(T).name());