Skip to content

Commit

Permalink
Logger -> MiniLogger; made less dependent on Crouton
Browse files Browse the repository at this point in the history
  • Loading branch information
snej committed Nov 26, 2023
1 parent 57642cd commit 658a0da
Show file tree
Hide file tree
Showing 11 changed files with 163 additions and 96 deletions.
4 changes: 2 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,10 @@ add_library( LibCrouton STATIC
src/support/Backtrace+Unix.cc
src/support/Backtrace+Windows.cc
src/support/betterassert.cc
src/support/Memoized.cc
src/support/Logger.cc
src/support/Logging.cc
src/support/Memoized.cc
src/support/MiniFormat.cc
src/support/MiniLogger.cc
src/support/MiniOStream.cc
src/support/StringUtils.cc
src/support/Varint.cc
Expand Down
12 changes: 6 additions & 6 deletions crouton.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@
27BCD3382AF30A20009DFCED /* libmbedcrypto.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 27BCD3352AF30A20009DFCED /* libmbedcrypto.a */; };
27E98EDF2AC2099E002F3D35 /* test_generator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 27E98EDE2AC2099E002F3D35 /* test_generator.cc */; };
27E9A0C72AFAB8FE00EF3726 /* Task.cc in Sources */ = {isa = PBXBuildFile; fileRef = 27E9A0C62AFAB8FE00EF3726 /* Task.cc */; };
27E9A0D62AFDAA6100EF3726 /* Logger.cc in Sources */ = {isa = PBXBuildFile; fileRef = 27E9A0D52AFDAA6100EF3726 /* Logger.cc */; };
27E9A0D62AFDAA6100EF3726 /* MiniLogger.cc in Sources */ = {isa = PBXBuildFile; fileRef = 27E9A0D52AFDAA6100EF3726 /* MiniLogger.cc */; };
27E9A1122B02C61A00EF3726 /* miniz_tinfl.c in Sources */ = {isa = PBXBuildFile; fileRef = 27E9A10B2B02C52C00EF3726 /* miniz_tinfl.c */; settings = {COMPILER_FLAGS = "-Wno-comma -O3"; }; };
27E9A1162B02CD1800EF3726 /* miniz_tdef.c in Sources */ = {isa = PBXBuildFile; fileRef = 27E9A0E72B02C52C00EF3726 /* miniz_tdef.c */; settings = {COMPILER_FLAGS = "-Wno-comma -O3"; }; };
27E9A1172B02CF9A00EF3726 /* miniz.c in Sources */ = {isa = PBXBuildFile; fileRef = 27E9A0E22B02C52C00EF3726 /* miniz.c */; settings = {COMPILER_FLAGS = "-Wno-comma -O3"; }; };
Expand Down Expand Up @@ -715,8 +715,8 @@
27E98EDE2AC2099E002F3D35 /* test_generator.cc */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = test_generator.cc; sourceTree = "<group>"; };
27E98EE02AC21940002F3D35 /* Awaitable.hh */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = Awaitable.hh; sourceTree = "<group>"; };
27E9A0C62AFAB8FE00EF3726 /* Task.cc */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = Task.cc; sourceTree = "<group>"; };
27E9A0D42AFDA91200EF3726 /* Logger.hh */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = Logger.hh; sourceTree = "<group>"; };
27E9A0D52AFDAA6100EF3726 /* Logger.cc */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = Logger.cc; sourceTree = "<group>"; };
27E9A0D42AFDA91200EF3726 /* MiniLogger.hh */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = MiniLogger.hh; sourceTree = "<group>"; };
27E9A0D52AFDAA6100EF3726 /* MiniLogger.cc */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = MiniLogger.cc; sourceTree = "<group>"; };
27E9A0E12B02C52C00EF3726 /* miniz_zip.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = miniz_zip.h; sourceTree = "<group>"; };
27E9A0E22B02C52C00EF3726 /* miniz.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = miniz.c; sourceTree = "<group>"; };
27E9A0E32B02C52C00EF3726 /* miniz_tinfl.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = miniz_tinfl.h; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1183,8 +1183,8 @@
27B3306A2AB391F30066C8DA /* Bytes.hh */,
2727304B2A8E811B000CCA22 /* Defer.hh */,
277E8A432ABA50FB00E78CB1 /* LinkedList.hh */,
27E9A0D42AFDA91200EF3726 /* Logger.hh */,
278F7F222AAA98FE005B12F2 /* Logging.hh */,
27E9A0D42AFDA91200EF3726 /* MiniLogger.hh */,
277B6C272AE06CDA006F053D /* MiniFormat.hh */,
2755E81C2B0947D40005AC35 /* MiniOStream.hh */,
277B65282AD766EF006F053D /* Relation.hh */,
Expand Down Expand Up @@ -1622,11 +1622,11 @@
27F49CD42A9E4E8E00BFB24C /* Backtrace.hh */,
277B652B2AD8B5D8006F053D /* betterassert.cc */,
27B330692AB388960066C8DA /* Endian.hh */,
27E9A0D52AFDAA6100EF3726 /* Logger.cc */,
278F7F232AAA98FE005B12F2 /* Logging.cc */,
275A5F132AAFB3B1009791E8 /* Memoized.hh */,
275A5F142AAFB3B1009791E8 /* Memoized.cc */,
277B6C282AE06CDA006F053D /* MiniFormat.cc */,
27E9A0D52AFDAA6100EF3726 /* MiniLogger.cc */,
2755E81D2B0947D40005AC35 /* MiniOStream.cc */,
278F7E3E2AA24FEE005B12F2 /* StringUtils.hh */,
27B330572AB278870066C8DA /* StringUtils.cc */,
Expand Down Expand Up @@ -1999,7 +1999,7 @@
272730482A8D8A73000CCA22 /* Scheduler.cc in Sources */,
2755E81F2B0947D40005AC35 /* MiniOStream.cc in Sources */,
277B652C2AD8B5D8006F053D /* betterassert.cc in Sources */,
27E9A0D62AFDAA6100EF3726 /* Logger.cc in Sources */,
27E9A0D62AFDAA6100EF3726 /* MiniLogger.cc in Sources */,
272730532A8EC61D000CCA22 /* FileStream.cc in Sources */,
272A852B2A97B2090083D947 /* HTTPConnection.cc in Sources */,
2727304E2A8E9D99000CCA22 /* UVBase.cc in Sources */,
Expand Down
2 changes: 1 addition & 1 deletion include/crouton/util/Bytes.hh
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ namespace crouton {


/** Low-level struct pointing to immutable data.
Usually serves as the source of a `write`, or as a returned buffer from `readNoCopy`. */
Usually serves as the source of a `write`, or as a returned buffer from `readNoCopy`. */
class ConstBytes : public Bytes<const byte, ConstBytes> {
public:
using Bytes::Bytes;
Expand Down
6 changes: 4 additions & 2 deletions include/crouton/util/Logging.hh
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

#pragma once

// By default, Crouton uses its own small logging library, defined in Logger.hh.
// By default, Crouton uses its own small logging library, defined in MiniLogger.hh.
// To make it use spdlog instead, pre-define the macro `CROUTON_USE_SPDLOG` to `1`.
#ifndef CROUTON_USE_SPDLOG
#define CROUTON_USE_SPDLOG 0
Expand All @@ -31,13 +31,15 @@
#include <spdlog/spdlog.h>
#include <spdlog/fmt/ostr.h> // Makes custom types loggable via `operator <<` overloads
#else
#include "crouton/util/Logger.hh"
#include "crouton/util/MiniLogger.hh"
#endif

namespace crouton {

#if CROUTON_USE_SPDLOG
namespace log = ::spdlog;
#else
namespace log = ::crouton::mini;
#endif


Expand Down
24 changes: 19 additions & 5 deletions include/crouton/util/MiniFormat.hh
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@
/*
A string formatting API mostly compatible with `std::format`, but optimized for small code size.
https://en.cppreference.com/w/cpp/utility/format/formatter
Missing functionality and limitations:
- You can't create custom formatters that interpret custom field specs. (But you can format
custom types by implementing `operator<<`.)
- Arguments can't be reordered (i.e. a field spec like `{nn:}` isn't allowed.)
- Field widths & alignment are not Unicode-aware; they assume 1 byte == 1 space.
- Localized variants are unimplemented (using 'L' in a format spec has no effect.)
- Only 10 arguments are allowed. (You can change this by changing BaseFormatString::kMaxSpecs.)
- Field width and precision are limited to 255.
Known bugs:
- When a number is zero-padded, the zeroes go before the sign character, not afterward.
- When the alternate ('#') form of a float adds a decimal point, it will go after any exponent,
when it should go before.
*/

namespace crouton::mini {
Expand Down Expand Up @@ -107,7 +121,7 @@ namespace crouton::mini {


/** A pointer to a C array of argument types, terminated with `None`.
This is constructed at compile-time and passed to the `format` implementation.*/
This is constructed at compile-time and passed to the `format` implementation. */
using ArgTypeList = i::ArgType const*;


Expand Down Expand Up @@ -213,17 +227,17 @@ namespace crouton::mini {
Spec const* _pSpec;
};

iterator begin() const Pure {return iterator(*this);}
iterator end() const Pure {return iterator(&_impl._lengths[_impl._nSegments]);}
iterator begin() const {return iterator(*this);}
iterator end() const {return iterator(&_impl._lengths[_impl._nSegments]);}

#ifndef NDEBUG
static BaseFormatString testParse(const char* cstr, ArgTypeList argTypes) {
return BaseFormatString(parse(cstr, argTypes));
}
#endif
private:
static constexpr size_t kMaxSegments = 15;
static constexpr size_t kMaxSpecs = 8;
static constexpr size_t kMaxSpecs = 10;
static constexpr size_t kMaxSegments = 2 * kMaxSpecs + 1;

struct Impl {
const char* const _str; // the format string
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// Logger.hh
// MiniLogger.hh
//
// Copyright 2023-Present Couchbase, Inc. All rights reserved.
//
Expand All @@ -16,16 +16,13 @@
// limitations under the License.
//

#if CROUTON_USE_SPDLOG != 0
#error "Don't include Logger.hh directly; include Logging.hh instead"
#endif

#pragma once
#include "crouton/util/Base.hh"
#include "crouton/util/MiniFormat.hh"
#include <functional>

namespace crouton::log {
namespace crouton::mini {
using std::string;
using std::string_view;

// Minimal logging API, mostly compatible with spdlog

Expand All @@ -36,24 +33,37 @@ namespace crouton::log {
};


/** A named logger, which can have its own level. */
class logger {
public:
logger(string name, level::level_enum level);
/// Constructs a logger with a name and a default initial level.
logger(string name, level::level_enum defaultLevel);
~logger() = delete;

string const& name() const Pure {return _name;}
level::level_enum level() const Pure {return _level;}
/// The logger's name.
string const& name() const {return _name;}

/// The logger's current level. Messages with a lower level will not be logged.
level::level_enum level() const {return _level;}

/// Sets the current level.
void set_level(level::level_enum level) {_level = level;}
bool should_log(level::level_enum level) const Pure {return level >= _level;}

/// Returns true if the logger will log messages at the given level.
bool should_log(level::level_enum level) const {return level >= _level;}

/// Logs a formatted message at the given level.
template<mini::Formattable... Args>
void log(level::level_enum lvl, mini::FormatString<Args...> const& fmt, Args &&...args) {
if (should_log(lvl)) [[unlikely]]
_log(lvl, fmt, mini::ArgTypes<Args...>::ids, mini::i::passArg(args)...);
}

/// Logs an unformatted message at the given level.
void log(level::level_enum lvl, string_view msg);

// The methods below all call `log` with the levels indicated by their names.

template<mini::Formattable... Args>
void trace(mini::FormatString<Args...> const& fmt, Args &&...args) {
log(level::trace, fmt, std::forward<Args>(args)...);
Expand Down Expand Up @@ -90,15 +100,29 @@ namespace crouton::log {
}
void critical(string_view msg) {log(level::critical, msg);}

/// Initializes levels based on the value of the `CROUTON_LOG_LEVEL` environment variable.
/// @note This just calls `load_env_levels(getenv("CROUTON_LOG_LEVEL"))`.
/// @note This function isn't available on ESP32 since it has no environment API.
static void load_env_levels();

/// Initializes levels based on the given string.
/// - First, the string is split into sections at commas.
/// - A section of the form "name=levelname" sets the level of the named logger.
/// - If no logger with that name exists yet, the level will be set when it's created.
/// - A section that's just "levelname" applies to all loggers that aren't explicitly named.
static void load_env_levels(const char *envValue);

/// Returns the logger with the given name, else nullptr.
static logger* get(string_view name);

/// Calls a function on every logger.
static void apply_all(std::function<void(logger&)>);

using Sink = void (*)(logger const&, level::level_enum, string_view) noexcept;

/// Registers a function that handles log messages.
/// If non-null, every log message triggers a call to this function, instead of the
/// default behavior of writing to `stderr`.
static void set_output(Sink);

private:
Expand Down
Loading

0 comments on commit 658a0da

Please sign in to comment.