Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[C++] Add C++ single file logger factory #10712

Merged
merged 5 commits into from
May 29, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pulsar-client-cpp/examples/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ set(SAMPLE_PRODUCER_SOURCES
SampleProducer.cc
)

set(SAMPLE_FILE_LOGGER_SOURCES
SampleFileLogger.cc
)

set(SAMPLE_PRODUCER_C_SOURCES
SampleProducerCApi.c
)
Expand All @@ -57,6 +61,7 @@ add_executable(SampleAsyncProducer ${SAMPLE_ASYNC_PRODUCER_SOURCES})
add_executable(SampleConsumer ${SAMPLE_CONSUMER_SOURCES})
add_executable(SampleConsumerListener ${SAMPLE_CONSUMER_LISTENER_SOURCES})
add_executable(SampleProducer ${SAMPLE_PRODUCER_SOURCES})
add_executable(SampleFileLogger ${SAMPLE_FILE_LOGGER_SOURCES})
add_executable(SampleProducerCApi ${SAMPLE_PRODUCER_C_SOURCES})
add_executable(SampleConsumerCApi ${SAMPLE_CONSUMER_C_SOURCES})
add_executable(SampleConsumerListenerCApi ${SAMPLE_CONSUMER_LISTENER_C_SOURCES})
Expand All @@ -66,6 +71,7 @@ target_link_libraries(SampleAsyncProducer ${CLIENT_LIBS} pulsarShared)
target_link_libraries(SampleConsumer ${CLIENT_LIBS} pulsarShared)
target_link_libraries(SampleConsumerListener ${CLIENT_LIBS} pulsarShared)
target_link_libraries(SampleProducer ${CLIENT_LIBS} pulsarShared)
target_link_libraries(SampleFileLogger ${CLIENT_LIBS} pulsarShared)
target_link_libraries(SampleProducerCApi ${CLIENT_LIBS} pulsarShared)
target_link_libraries(SampleConsumerCApi ${CLIENT_LIBS} pulsarShared)
target_link_libraries(SampleConsumerListenerCApi ${CLIENT_LIBS} pulsarShared)
Expand Down
2 changes: 1 addition & 1 deletion pulsar-client-cpp/examples/SampleAsyncProducer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ int main() {
Client client("pulsar://localhost:6650");

Producer producer;
Result result = client.createProducer("persistent://prop/r1/ns1/my-topic", producer);
Result result = client.createProducer("persistent://public/default/my-topic", producer);
if (result != ResultOk) {
LOG_ERROR("Error creating producer: " << result);
return -1;
Expand Down
2 changes: 1 addition & 1 deletion pulsar-client-cpp/examples/SampleConsumer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ int main() {
Client client("pulsar://localhost:6650");

Consumer consumer;
Result result = client.subscribe("persistent://prop/r1/ns1/my-topic", "consumer-1", consumer);
Result result = client.subscribe("persistent://public/default/my-topic", "consumer-1", consumer);
if (result != ResultOk) {
LOG_ERROR("Failed to subscribe: " << result);
return -1;
Expand Down
2 changes: 1 addition & 1 deletion pulsar-client-cpp/examples/SampleConsumerListener.cc
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ int main() {
Consumer consumer;
ConsumerConfiguration config;
config.setMessageListener(listener);
Result result = client.subscribe("persistent://prop/r1/ns1/my-topic", "consumer-1", config, consumer);
Result result = client.subscribe("persistent://public/default/my-topic", "consumer-1", config, consumer);
if (result != ResultOk) {
LOG_ERROR("Failed to subscribe: " << result);
return -1;
Expand Down
111 changes: 111 additions & 0 deletions pulsar-client-cpp/examples/SampleFileLogger.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <string.h>

#include <chrono>
#include <ctime>
#include <fstream>
#include <sstream>
#include <thread>

#include <pulsar/Client.h>

class FileLogger : public pulsar::Logger {
public:
FileLogger(std::ofstream& os, Level level, const std::string& filename)
: os_(os), level_(level), filename_(filename) {}

bool isEnabled(Level level) override { return level >= level_; }

void log(Level level, int line, const std::string& message) override {
std::ostringstream oss;
auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
oss << currentTime() << " " << convertLevelToString(level) << " [" << std::this_thread::get_id()
<< "] " << filename_ << ":" << line << " " << message << "\n";
os_ << oss.str();
os_.flush();
}

private:
std::ostream& os_;
const Level level_;
const std::string filename_;

static const char* currentTime() {
auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char* s = ctime(&now); // ctime() returns a string with a newline at the end
auto newLinePos = strlen(s) - 1;
s[newLinePos] = '\0';
return s;
}

static const char* convertLevelToString(Level level) {
switch (level) {
case Level::LEVEL_DEBUG:
return "DEBUG";
case Level::LEVEL_INFO:
return "INFO";
case Level::LEVEL_WARN:
return "WARN";
case Level::LEVEL_ERROR:
return "ERROR";
default:
return "???";
}
}
};

/**
* A logger factory that is appending logs to a single file.
*/
class SingleFileLoggerFactory : public pulsar::LoggerFactory {
BewareMyPower marked this conversation as resolved.
Show resolved Hide resolved
public:
/**
* Create a SingleFileLoggerFactory instance.
*
* @param level the log level
* @param logFilePath the log file's path
*/
SingleFileLoggerFactory(pulsar::Logger::Level level, const std::string& logFilePath)
: level_(level), os_(logFilePath, std::ios_base::out | std::ios_base::app) {}

~SingleFileLoggerFactory() { os_.close(); }

virtual pulsar::Logger* getLogger(const std::string& filename) override {
return new FileLogger(os_, level_, filename);
}

private:
const pulsar::Logger::Level level_;
std::ofstream os_;
};

using namespace pulsar;

int main(int argc, char* argv[]) {
ClientConfiguration clientConf;
// The logs whose level is >= INFO will be written to pulsar-cpp-client.log
clientConf.setLogger(new SingleFileLoggerFactory(Logger::Level::LEVEL_INFO, "pulsar-cpp-client.log"));

Client client("pulsar://localhost:6650", clientConf);
Producer producer;
client.createProducer("my-topic", producer); // just to create some logs
client.close();
return 0;
}
2 changes: 1 addition & 1 deletion pulsar-client-cpp/examples/SampleProducer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ int main() {
Client client("pulsar://localhost:6650");

Producer producer;
Result result = client.createProducer("persistent://prop/r1/ns1/my-topic", producer);
Result result = client.createProducer("persistent://public/default/my-topic", producer);
if (result != ResultOk) {
LOG_ERROR("Error creating producer: " << result);
return -1;
Expand Down