Skip to content

Commit 8620976

Browse files
committed
feat(console): frame split messages with a header the CLI asks for
Replaces the invisible end-of-chunk markers and the logChunkMarkers key. When a message has to be split and the app's package.json has a logFormat of 1 or more (with stdout going to /dev/null, as when the CLI launches the app), each piece is logged as "[ns <id> <index>/<count>] <piece>". The id is unique per message in the process. The pieces are consecutive slices of the message and only the first carries the console prefix, so they join back as they are. The unified log strips whitespace from the end of every entry, so a piece never ends in whitespace: the cut moves before it and the whitespace starts the next piece, behind its header. With the id, index and count, the CLI can tell pieces apart by message instead of by thread, notice a lost piece instead of joining the next message onto an unfinished one, and print a message as soon as its last piece arrives. logFormat holds the newest format the CLI understands; the runtime uses the lower of that and its own. Without the key, split messages are logged as before: plain lines, each with the prefix repeated.
1 parent 53993e1 commit 8620976

3 files changed

Lines changed: 139 additions & 28 deletions

File tree

‎NativeScript/runtime/Helpers.h‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -355,24 +355,38 @@ void LogBacktrace(int skip = 1);
355355
// "%{public}s" argument to os_log. When os_log is not available we
356356
// fall back to NSLog (Objective-C) or CF/NSLog bridge in pure C++ builds.
357357

358-
// Whether split messages should carry markers for the CLI to stitch them with.
359-
bool ShouldMarkLogChunks();
358+
// The log format (see LogChunks.h) the CLI asked for, or 0 for plain split lines.
359+
int LogFormat();
360+
361+
// Unique per split message in the process, for the headers of format 1.
362+
uint32_t NextLogMessageId();
360363

361364
#if TNS_HAVE_OS_LOG
362-
// The prefix is repeated on every chunk, so that each stays a complete log line.
365+
// Logs the two parts as one entry.
366+
static inline void TNS_WriteOsLogEntry(os_log_type_t type, std::string_view first,
367+
std::string_view second) {
368+
os_log_with_type(OS_LOG_DEFAULT, type, "%{public}.*s%{public}.*s",
369+
static_cast<int>(first.size()), first.data(), static_cast<int>(second.size()),
370+
second.data());
371+
}
372+
363373
static inline void TNS_WriteToOsLog(const char* message, os_log_type_t type = OS_LOG_TYPE_DEFAULT,
364374
std::string_view prefix = "") {
365-
ForEachLogChunk(message, kMaxLogChunkBytes - prefix.size(),
366-
[&](std::string_view chunk, LogChunkBreak chunkBreak) {
367-
const char* marker = "";
368-
if (chunkBreak != LogChunkBreak::kNone && ShouldMarkLogChunks()) {
369-
marker = chunkBreak == LogChunkBreak::kLine ? kLogChunkLineMarker
370-
: kLogChunkJoinMarker;
371-
}
372-
os_log_with_type(OS_LOG_DEFAULT, type, "%{public}.*s%{public}.*s%{public}s",
373-
static_cast<int>(prefix.size()), prefix.data(),
374-
static_cast<int>(chunk.size()), chunk.data(), marker);
375-
});
375+
std::string_view text(message);
376+
if (prefix.size() + text.size() <= kMaxLogChunkBytes) {
377+
TNS_WriteOsLogEntry(type, prefix, text);
378+
} else if (LogFormat() >= 1) {
379+
ForEachFramedLogChunk(prefix, text, NextLogMessageId(),
380+
[&](std::string_view header, std::string_view piece) {
381+
TNS_WriteOsLogEntry(type, header, piece);
382+
});
383+
} else {
384+
// Repeated on every piece, so that each stays a complete log line.
385+
ForEachLogChunk(text, kMaxLogChunkBytes - prefix.size(),
386+
[&](std::string_view chunk, LogChunkBreak) {
387+
TNS_WriteOsLogEntry(type, prefix, chunk);
388+
});
389+
}
376390
}
377391
#endif
378392

‎NativeScript/runtime/Helpers.mm‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <stdlib.h>
1010
#include <sys/stat.h>
1111
#include <unistd.h>
12+
#include <algorithm>
1213
#include <atomic>
1314
#include <cerrno>
1415
#include <mutex>
@@ -500,19 +501,26 @@ static bool IsDevNull(int fd) {
500501
S_ISCHR(target.st_mode) && target.st_rdev == devNull.st_rdev;
501502
}
502503

503-
// Syslog-style output shows the markers as visible text and an attached console
504-
// shows them as they are, so they need a CLI that asked for them and no console.
505-
bool tns::ShouldMarkLogChunks() {
504+
// A console attached to the app would show the headers, so they also need stdout
505+
// to go nowhere, as it does when the CLI launches the app.
506+
int tns::LogFormat() {
506507
if (RuntimeConfig.ApplicationPath.empty()) {
507-
return false;
508+
return 0;
508509
}
509510

510-
static const bool enabled = [] {
511-
id value = Runtime::GetAppConfigValue("logChunkMarkers");
512-
return [value isKindOfClass:[NSNumber class]] && [value boolValue] &&
513-
IsDevNull(STDOUT_FILENO);
511+
static const int format = [] {
512+
id value = Runtime::GetAppConfigValue("logFormat");
513+
if (![value isKindOfClass:[NSNumber class]] || !IsDevNull(STDOUT_FILENO)) {
514+
return 0;
515+
}
516+
return std::clamp([value intValue], 0, kNewestLogFormat);
514517
}();
515-
return enabled;
518+
return format;
519+
}
520+
521+
uint32_t tns::NextLogMessageId() {
522+
static std::atomic<uint32_t> lastMessageId{0};
523+
return lastMessageId.fetch_add(1, std::memory_order_relaxed) + 1;
516524
}
517525

518526
void tns::EmitDebugLog(LogCategory category, const char* format, ...) {

‎NativeScript/runtime/LogChunks.h‎

Lines changed: 94 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
#define LogChunks_h
33

44
#include <cstddef>
5+
#include <cstdint>
6+
#include <cstdio>
7+
#include <string>
58
#include <string_view>
9+
#include <vector>
610

711
namespace tns {
812

@@ -14,11 +18,6 @@ constexpr size_t kMaxLogChunkBytes = 900;
1418
// How a chunk connects to the one after it.
1519
enum class LogChunkBreak { kNone, kJoin, kLine };
1620

17-
// Invisible, so that the chunks read normally wherever they are not stitched.
18-
// Control characters would not do: os_log escapes them.
19-
constexpr const char* kLogChunkJoinMarker = "\u2060";
20-
constexpr const char* kLogChunkLineMarker = "\u2061";
21-
2221
// Calls emit with consecutive pieces of message, each at most maxBytes long and
2322
// never ending inside a UTF-8 sequence. A piece ends at the last line break that
2423
// fits, so that lines stay intact whenever they can; that line break is dropped,
@@ -50,6 +49,96 @@ void ForEachLogChunk(std::string_view message, size_t maxBytes, Emit&& emit) {
5049
emit(message, LogChunkBreak::kNone);
5150
}
5251

52+
// The newest value of the logFormat key in the app's package.json that the
53+
// runtime understands. The CLI writes the newest one it understands.
54+
//
55+
// Format 1 logs each piece of a split message as "[ns <id> <index>/<count>] "
56+
// followed by the piece. <id> is unique per message in the process (hex) and
57+
// <index> counts from 1. The pieces are consecutive slices of the message and
58+
// only the first carries the message's prefix, so they join back into the
59+
// message as they are. Messages that fit in one entry are logged without a
60+
// header.
61+
constexpr int kNewestLogFormat = 1;
62+
63+
// Room for the longest header: ids up to 8 hex digits and counts up to 7
64+
// decimal ones (messages of several GB).
65+
constexpr size_t kMaxLogChunkHeaderBytes = 40;
66+
67+
inline std::string_view FormatLogChunkHeader(char (&buffer)[kMaxLogChunkHeaderBytes], uint32_t id,
68+
size_t index, size_t count) {
69+
int length = snprintf(buffer, sizeof(buffer), "[ns %x %zu/%zu] ", id, index, count);
70+
if (length < 0) {
71+
return {};
72+
}
73+
return std::string_view(buffer, static_cast<size_t>(length) < sizeof(buffer)
74+
? static_cast<size_t>(length)
75+
: sizeof(buffer) - 1);
76+
}
77+
78+
inline bool IsLogWhitespace(char c) {
79+
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f';
80+
}
81+
82+
// Calls emit with consecutive slices of text, each at most maxBytes long and
83+
// never ending inside a UTF-8 sequence. The unified log strips whitespace from
84+
// the end of every entry, so a slice never ends in whitespace: it is left for
85+
// the start of the next slice, behind that slice's header. Only a run of
86+
// whitespace longer than maxBytes still loses what it ends with. A slice ends
87+
// before the last line break that fits, so that lines stay intact whenever they
88+
// can.
89+
template <typename Emit>
90+
void ForEachLogSlice(std::string_view text, size_t maxBytes, Emit&& emit) {
91+
auto backOverWhitespace = [&](size_t end) {
92+
while (end > 0 && IsLogWhitespace(text[end - 1])) {
93+
end--;
94+
}
95+
return end;
96+
};
97+
98+
while (text.size() > maxBytes) {
99+
size_t lineBreak = text.rfind('\n', maxBytes);
100+
size_t end = lineBreak == std::string_view::npos ? 0 : backOverWhitespace(lineBreak);
101+
102+
if (end == 0) {
103+
end = maxBytes;
104+
while (end > 0 && (static_cast<unsigned char>(text[end]) & 0xC0) == 0x80) {
105+
end--;
106+
}
107+
// Not UTF-8 at all: any cut is as good as another.
108+
if (end == 0) {
109+
end = maxBytes;
110+
}
111+
if (size_t beforeWhitespace = backOverWhitespace(end)) {
112+
end = beforeWhitespace;
113+
}
114+
}
115+
116+
emit(text.substr(0, end));
117+
text.remove_prefix(end);
118+
}
119+
120+
emit(text);
121+
}
122+
123+
// Calls emit with the header and text of each piece of prefix + message, split
124+
// in format 1 as the message with the given id.
125+
template <typename Emit>
126+
void ForEachFramedLogChunk(std::string_view prefix, std::string_view message, uint32_t id,
127+
Emit&& emit) {
128+
std::string text;
129+
text.reserve(prefix.size() + message.size());
130+
text.append(prefix).append(message);
131+
132+
std::vector<std::string_view> pieces;
133+
ForEachLogSlice(text, kMaxLogChunkBytes - kMaxLogChunkHeaderBytes,
134+
[&](std::string_view piece) { pieces.push_back(piece); });
135+
136+
for (size_t i = 0; i < pieces.size(); i++) {
137+
char buffer[kMaxLogChunkHeaderBytes];
138+
emit(FormatLogChunkHeader(buffer, id, i + 1, pieces.size()), pieces[i]);
139+
}
140+
}
141+
53142
} // namespace tns
54143

55144
#endif /* LogChunks_h */

0 commit comments

Comments
 (0)