Path: blob/master/src/hotspot/share/logging/logConfiguration.cpp
40930 views
/*1* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/23#include "precompiled.hpp"24#include "jvm.h"25#include "logging/log.hpp"26#include "logging/logAsyncWriter.hpp"27#include "logging/logConfiguration.hpp"28#include "logging/logDecorations.hpp"29#include "logging/logDecorators.hpp"30#include "logging/logDiagnosticCommand.hpp"31#include "logging/logFileOutput.hpp"32#include "logging/logOutput.hpp"33#include "logging/logSelectionList.hpp"34#include "logging/logStream.hpp"35#include "logging/logTagSet.hpp"36#include "memory/allocation.inline.hpp"37#include "memory/resourceArea.hpp"38#include "runtime/os.hpp"39#include "runtime/semaphore.hpp"40#include "utilities/globalDefinitions.hpp"4142LogOutput** LogConfiguration::_outputs = NULL;43size_t LogConfiguration::_n_outputs = 0;4445LogConfiguration::UpdateListenerFunction* LogConfiguration::_listener_callbacks = NULL;46size_t LogConfiguration::_n_listener_callbacks = 0;4748// LogFileOutput is the default type of output, its type prefix should be used if no type was specified49static const char* implicit_output_prefix = LogFileOutput::Prefix;5051// Stack object to take the lock for configuring the logging.52// Should only be held during the critical parts of the configuration53// (when calling configure_output or reading/modifying the outputs array).54// Thread must never block when holding this lock.55class ConfigurationLock : public StackObj {56private:57// Semaphore used as lock58static Semaphore _semaphore;59debug_only(static intx _locking_thread_id;)60public:61ConfigurationLock() {62_semaphore.wait();63debug_only(_locking_thread_id = os::current_thread_id());64}65~ConfigurationLock() {66debug_only(_locking_thread_id = -1);67_semaphore.signal();68}69debug_only(static bool current_thread_has_lock();)70};7172Semaphore ConfigurationLock::_semaphore(1);73#ifdef ASSERT74intx ConfigurationLock::_locking_thread_id = -1;75bool ConfigurationLock::current_thread_has_lock() {76return _locking_thread_id == os::current_thread_id();77}78#endif7980void LogConfiguration::post_initialize() {81// Reset the reconfigured status of all outputs82for (size_t i = 0; i < _n_outputs; i++) {83_outputs[i]->_reconfigured = false;84}8586LogDiagnosticCommand::registerCommand();87Log(logging) log;88if (log.is_info()) {89log.info("Log configuration fully initialized.");90log_develop_info(logging)("Develop logging is available.");9192LogStream info_stream(log.info());93describe_available(&info_stream);9495LogStream debug_stream(log.debug());96LogTagSet::list_all_tagsets(&debug_stream);9798ConfigurationLock cl;99describe_current_configuration(&info_stream);100}101}102103void LogConfiguration::initialize(jlong vm_start_time) {104LogFileOutput::set_file_name_parameters(vm_start_time);105assert(_outputs == NULL, "Should not initialize _outputs before this function, initialize called twice?");106_outputs = NEW_C_HEAP_ARRAY(LogOutput*, 2, mtLogging);107_outputs[0] = &StdoutLog;108_outputs[1] = &StderrLog;109_n_outputs = 2;110}111112void LogConfiguration::finalize() {113disable_outputs();114FREE_C_HEAP_ARRAY(LogOutput*, _outputs);115}116117// Normalizes the given LogOutput name to type=name form.118// For example, foo, "foo", file="foo", will all be normalized to file=foo (no quotes, prefixed).119static bool normalize_output_name(const char* full_name, char* buffer, size_t len, outputStream* errstream) {120const char* start_quote = strchr(full_name, '"');121const char* equals = strchr(full_name, '=');122const bool quoted = start_quote != NULL;123const bool is_stdout_or_stderr = (strcmp(full_name, "stdout") == 0 || strcmp(full_name, "stderr") == 0);124125// ignore equals sign within quotes126if (quoted && equals > start_quote) {127equals = NULL;128}129130const char* prefix = "";131size_t prefix_len = 0;132const char* name = full_name;133if (equals != NULL) {134// split on equals sign135name = equals + 1;136prefix = full_name;137prefix_len = equals - full_name + 1;138} else if (!is_stdout_or_stderr) {139prefix = implicit_output_prefix;140prefix_len = strlen(prefix);141}142size_t name_len = strlen(name);143144if (quoted) {145const char* end_quote = strchr(start_quote + 1, '"');146if (end_quote == NULL) {147errstream->print_cr("Output name has opening quote but is missing a terminating quote.");148return false;149}150if (start_quote != name || end_quote[1] != '\0') {151errstream->print_cr("Output name can not be partially quoted."152" Either surround the whole name with quotation marks,"153" or do not use quotation marks at all.");154return false;155}156// strip start and end quote157name++;158name_len -= 2;159}160161int ret = jio_snprintf(buffer, len, "%.*s%.*s", prefix_len, prefix, name_len, name);162assert(ret > 0, "buffer issue");163return true;164}165166size_t LogConfiguration::find_output(const char* name) {167for (size_t i = 0; i < _n_outputs; i++) {168if (strcmp(_outputs[i]->name(), name) == 0) {169return i;170}171}172return SIZE_MAX;173}174175LogOutput* LogConfiguration::new_output(const char* name,176const char* options,177outputStream* errstream) {178LogOutput* output;179if (strncmp(name, LogFileOutput::Prefix, strlen(LogFileOutput::Prefix)) == 0) {180output = new LogFileOutput(name);181} else {182errstream->print_cr("Unsupported log output type: %s", name);183return NULL;184}185186bool success = output->initialize(options, errstream);187if (!success) {188errstream->print_cr("Initialization of output '%s' using options '%s' failed.", name, options);189delete output;190return NULL;191}192return output;193}194195size_t LogConfiguration::add_output(LogOutput* output) {196size_t idx = _n_outputs++;197_outputs = REALLOC_C_HEAP_ARRAY(LogOutput*, _outputs, _n_outputs, mtLogging);198_outputs[idx] = output;199return idx;200}201202void LogConfiguration::delete_output(size_t idx) {203assert(idx > 1 && idx < _n_outputs,204"idx must be in range 1 < idx < _n_outputs, but idx = " SIZE_FORMAT205" and _n_outputs = " SIZE_FORMAT, idx, _n_outputs);206LogOutput* output = _outputs[idx];207// Swap places with the last output and shrink the array208_outputs[idx] = _outputs[--_n_outputs];209_outputs = REALLOC_C_HEAP_ARRAY(LogOutput*, _outputs, _n_outputs, mtLogging);210delete output;211}212213void LogConfiguration::configure_output(size_t idx, const LogSelectionList& selections, const LogDecorators& decorators) {214assert(ConfigurationLock::current_thread_has_lock(), "Must hold configuration lock to call this function.");215assert(idx < _n_outputs, "Invalid index, idx = " SIZE_FORMAT " and _n_outputs = " SIZE_FORMAT, idx, _n_outputs);216LogOutput* output = _outputs[idx];217218output->_reconfigured = true;219220size_t on_level[LogLevel::Count] = {0};221222bool enabled = false;223for (LogTagSet* ts = LogTagSet::first(); ts != NULL; ts = ts->next()) {224LogLevelType level = selections.level_for(*ts);225226// Ignore tagsets that do not, and will not log on the output227if (!ts->has_output(output) && (level == LogLevel::NotMentioned || level == LogLevel::Off)) {228on_level[LogLevel::Off]++;229continue;230}231232// Update decorators before adding/updating output level,233// so that the tagset will have the necessary decorators when requiring them.234if (level != LogLevel::Off) {235ts->update_decorators(decorators);236}237238// Set the new level, if it changed239if (level != LogLevel::NotMentioned) {240ts->set_output_level(output, level);241} else {242// Look up the previously set level for this output on this tagset243level = ts->level_for(output);244}245246if (level != LogLevel::Off) {247// Keep track of whether or not the output is ever used by some tagset248enabled = true;249}250251// Track of the number of tag sets on each level252on_level[level]++;253}254255// It is now safe to set the new decorators for the actual output256output->set_decorators(decorators);257258// Update the decorators on all tagsets to get rid of unused decorators259for (LogTagSet* ts = LogTagSet::first(); ts != NULL; ts = ts->next()) {260ts->update_decorators();261}262263if (!enabled && idx > 1) {264// User may disable a logOuput like this:265// LogConfiguration::parse_log_arguments(filename, "all=off", "", "", &stream);266// Just be conservative. Flush them all before deleting idx.267AsyncLogWriter::flush();268// Output is unused and should be removed, unless it is stdout/stderr (idx < 2)269delete_output(idx);270return;271}272273output->update_config_string(on_level);274assert(strlen(output->config_string()) > 0, "should always have a config description");275}276277void LogConfiguration::disable_outputs() {278size_t idx = _n_outputs;279280// Remove all outputs from all tagsets.281for (LogTagSet* ts = LogTagSet::first(); ts != NULL; ts = ts->next()) {282ts->disable_outputs();283}284285// Handle jcmd VM.log disable286// ts->disable_outputs() above has deleted output_list with RCU synchronization.287// Therefore, no new logging entry can enter AsyncLog buffer for the time being.288// flush pending entries before LogOutput instances die.289AsyncLogWriter::flush();290291while (idx > 0) {292LogOutput* out = _outputs[--idx];293// Delete the output unless stdout or stderr (idx 0 or 1)294if (idx > 1) {295delete_output(idx);296} else {297out->set_config_string("all=off");298}299}300}301302void LogConfiguration::disable_logging() {303ConfigurationLock cl;304disable_outputs();305// Update the decorators on all tagsets to get rid of unused decorators306for (LogTagSet* ts = LogTagSet::first(); ts != NULL; ts = ts->next()) {307ts->update_decorators();308}309notify_update_listeners();310}311312void LogConfiguration::configure_stdout(LogLevelType level, int exact_match, ...) {313size_t i;314va_list ap;315LogTagType tags[LogTag::MaxTags];316va_start(ap, exact_match);317for (i = 0; i < LogTag::MaxTags; i++) {318LogTagType tag = static_cast<LogTagType>(va_arg(ap, int));319tags[i] = tag;320if (tag == LogTag::__NO_TAG) {321assert(i > 0, "Must specify at least one tag!");322break;323}324}325assert(i < LogTag::MaxTags || static_cast<LogTagType>(va_arg(ap, int)) == LogTag::__NO_TAG,326"Too many tags specified! Can only have up to " SIZE_FORMAT " tags in a tag set.", LogTag::MaxTags);327va_end(ap);328329LogSelection selection(tags, !exact_match, level);330assert(selection.tag_sets_selected() > 0,331"configure_stdout() called with invalid/non-existing log selection");332LogSelectionList list(selection);333334// Apply configuration to stdout (output #0), with the same decorators as before.335ConfigurationLock cl;336configure_output(0, list, _outputs[0]->decorators());337notify_update_listeners();338}339340bool LogConfiguration::parse_command_line_arguments(const char* opts) {341char* copy = os::strdup_check_oom(opts, mtLogging);342343// Split the option string to its colon separated components.344char* str = copy;345char* substrings[4] = {0};346for (int i = 0 ; i < 4; i++) {347substrings[i] = str;348349// Find the next colon or quote350char* next = strpbrk(str, ":\"");351#ifdef _WINDOWS352// Skip over Windows paths such as "C:\..."353// Handle both C:\... and file=C:\..."354if (next != NULL && next[0] == ':' && next[1] == '\\') {355if (next == str + 1 || (strncmp(str, "file=", 5) == 0)) {356next = strpbrk(next + 1, ":\"");357}358}359#endif360while (next != NULL && *next == '"') {361char* end_quote = strchr(next + 1, '"');362if (end_quote == NULL) {363log_error(logging)("Missing terminating quote in -Xlog option '%s'", str);364os::free(copy);365return false;366}367// Keep searching after the quoted substring368next = strpbrk(end_quote + 1, ":\"");369}370371if (next != NULL) {372*next = '\0';373str = next + 1;374} else {375str = NULL;376break;377}378}379380if (str != NULL) {381log_warning(logging)("Ignoring excess -Xlog options: \"%s\"", str);382}383384// Parse and apply the separated configuration options385char* what = substrings[0];386char* output = substrings[1];387char* decorators = substrings[2];388char* output_options = substrings[3];389char errbuf[512];390stringStream ss(errbuf, sizeof(errbuf));391bool success = parse_log_arguments(output, what, decorators, output_options, &ss);392393if (ss.size() > 0) {394// If it failed, log the error. If it didn't fail, but something was written395// to the stream, log it as a warning.396LogLevelType level = success ? LogLevel::Warning : LogLevel::Error;397398Log(logging) log;399char* start = errbuf;400char* end = strchr(start, '\n');401assert(end != NULL, "line must end with newline '%s'", start);402do {403assert(start < errbuf + sizeof(errbuf) &&404end < errbuf + sizeof(errbuf),405"buffer overflow");406*end = '\0';407log.write(level, "%s", start);408start = end + 1;409end = strchr(start, '\n');410assert(end != NULL || *start == '\0', "line must end with newline '%s'", start);411} while (end != NULL);412}413414os::free(copy);415return success;416}417418bool LogConfiguration::parse_log_arguments(const char* outputstr,419const char* selectionstr,420const char* decoratorstr,421const char* output_options,422outputStream* errstream) {423assert(errstream != NULL, "errstream can not be NULL");424if (outputstr == NULL || strlen(outputstr) == 0) {425outputstr = "stdout";426}427428LogSelectionList selections;429if (!selections.parse(selectionstr, errstream)) {430return false;431}432433LogDecorators decorators;434if (!decorators.parse(decoratorstr, errstream)) {435return false;436}437438ConfigurationLock cl;439size_t idx;440bool added = false;441if (outputstr[0] == '#') { // Output specified using index442int ret = sscanf(outputstr + 1, SIZE_FORMAT, &idx);443if (ret != 1 || idx >= _n_outputs) {444errstream->print_cr("Invalid output index '%s'", outputstr);445return false;446}447} else { // Output specified using name448// Normalize the name, stripping quotes and ensures it includes type prefix449size_t len = strlen(outputstr) + strlen(implicit_output_prefix) + 1;450char* normalized = NEW_C_HEAP_ARRAY(char, len, mtLogging);451if (!normalize_output_name(outputstr, normalized, len, errstream)) {452return false;453}454455idx = find_output(normalized);456if (idx == SIZE_MAX) {457// Attempt to create and add the output458LogOutput* output = new_output(normalized, output_options, errstream);459if (output != NULL) {460idx = add_output(output);461added = true;462}463}464465FREE_C_HEAP_ARRAY(char, normalized);466if (idx == SIZE_MAX) {467return false;468}469}470if (!added && output_options != NULL && strlen(output_options) > 0) {471errstream->print_cr("Output options for existing outputs are ignored.");472}473configure_output(idx, selections, decorators);474notify_update_listeners();475selections.verify_selections(errstream);476return true;477}478479void LogConfiguration::describe_available(outputStream* out) {480out->print("Available log levels:");481for (size_t i = 0; i < LogLevel::Count; i++) {482out->print("%s %s", (i == 0 ? "" : ","), LogLevel::name(static_cast<LogLevelType>(i)));483}484out->cr();485486out->print("Available log decorators:");487for (size_t i = 0; i < LogDecorators::Count; i++) {488LogDecorators::Decorator d = static_cast<LogDecorators::Decorator>(i);489out->print("%s %s (%s)", (i == 0 ? "" : ","), LogDecorators::name(d), LogDecorators::abbreviation(d));490}491out->cr();492493out->print("Available log tags:");494LogTag::list_tags(out);495496LogTagSet::describe_tagsets(out);497}498499void LogConfiguration::describe_current_configuration(outputStream* out) {500out->print_cr("Log output configuration:");501for (size_t i = 0; i < _n_outputs; i++) {502out->print(" #" SIZE_FORMAT ": ", i);503_outputs[i]->describe(out);504if (_outputs[i]->is_reconfigured()) {505out->print(" (reconfigured)");506}507out->cr();508}509}510511void LogConfiguration::describe(outputStream* out) {512describe_available(out);513ConfigurationLock cl;514describe_current_configuration(out);515}516517void LogConfiguration::print_command_line_help(outputStream* out) {518out->print_cr("-Xlog Usage: -Xlog[:[selections][:[output][:[decorators][:output-options]]]]");519out->print_cr("\t where 'selections' are combinations of tags and levels of the form tag1[+tag2...][*][=level][,...]");520out->print_cr("\t NOTE: Unless wildcard (*) is specified, only log messages tagged with exactly the tags specified will be matched.");521out->cr();522523out->print_cr("Available log levels:");524for (size_t i = 0; i < LogLevel::Count; i++) {525out->print("%s %s", (i == 0 ? "" : ","), LogLevel::name(static_cast<LogLevelType>(i)));526}527out->cr();528out->cr();529530out->print_cr("Available log decorators: ");531for (size_t i = 0; i < LogDecorators::Count; i++) {532LogDecorators::Decorator d = static_cast<LogDecorators::Decorator>(i);533out->print("%s %s (%s)", (i == 0 ? "" : ","), LogDecorators::name(d), LogDecorators::abbreviation(d));534}535out->cr();536out->print_cr(" Decorators can also be specified as 'none' for no decoration.");537out->cr();538539out->print_cr("Available log tags:");540LogTag::list_tags(out);541out->print_cr(" Specifying 'all' instead of a tag combination matches all tag combinations.");542out->cr();543544LogTagSet::describe_tagsets(out);545546out->print_cr("\nAvailable log outputs:");547out->print_cr(" stdout/stderr");548out->print_cr(" file=<filename>");549out->print_cr(" If the filename contains %%p and/or %%t, they will expand to the JVM's PID and startup timestamp, respectively.");550out->print_cr(" Additional output-options for file outputs:");551out->print_cr(" filesize=.. - Target byte size for log rotation (supports K/M/G suffix)."552" If set to 0, log rotation will not trigger automatically,"553" but can be performed manually (see the VM.log DCMD).");554out->print_cr(" filecount=.. - Number of files to keep in rotation (not counting the active file)."555" If set to 0, log rotation is disabled."556" This will cause existing log files to be overwritten.");557out->cr();558out->print_cr("\nAsynchronous logging (off by default):");559out->print_cr(" -Xlog:async");560out->print_cr(" All log messages are written to an intermediate buffer first and will then be flushed"561" to the corresponding log outputs by a standalone thread. Write operations at logsites are"562" guaranteed non-blocking.");563out->cr();564565out->print_cr("Some examples:");566out->print_cr(" -Xlog");567out->print_cr("\t Log all messages up to 'info' level to stdout with 'uptime', 'levels' and 'tags' decorations.");568out->print_cr("\t (Equivalent to -Xlog:all=info:stdout:uptime,levels,tags).");569out->cr();570571out->print_cr(" -Xlog:gc");572out->print_cr("\t Log messages tagged with 'gc' tag up to 'info' level to stdout, with default decorations.");573out->cr();574575out->print_cr(" -Xlog:gc,safepoint");576out->print_cr("\t Log messages tagged either with 'gc' or 'safepoint' tags, both up to 'info' level, to stdout, with default decorations.");577out->print_cr("\t (Messages tagged with both 'gc' and 'safepoint' will not be logged.)");578out->cr();579580out->print_cr(" -Xlog:gc+ref=debug");581out->print_cr("\t Log messages tagged with both 'gc' and 'ref' tags, up to 'debug' level, to stdout, with default decorations.");582out->print_cr("\t (Messages tagged only with one of the two tags will not be logged.)");583out->cr();584585out->print_cr(" -Xlog:gc=debug:file=gc.txt:none");586out->print_cr("\t Log messages tagged with 'gc' tag up to 'debug' level to file 'gc.txt' with no decorations.");587out->cr();588589out->print_cr(" -Xlog:gc=trace:file=gctrace.txt:uptimemillis,pid:filecount=5,filesize=1m");590out->print_cr("\t Log messages tagged with 'gc' tag up to 'trace' level to a rotating fileset of 5 files of size 1MB,");591out->print_cr("\t using the base name 'gctrace.txt', with 'uptimemillis' and 'pid' decorations.");592out->cr();593594out->print_cr(" -Xlog:gc::uptime,tid");595out->print_cr("\t Log messages tagged with 'gc' tag up to 'info' level to output 'stdout', using 'uptime' and 'tid' decorations.");596out->cr();597598out->print_cr(" -Xlog:gc*=info,safepoint*=off");599out->print_cr("\t Log messages tagged with at least 'gc' up to 'info' level, but turn off logging of messages tagged with 'safepoint'.");600out->print_cr("\t (Messages tagged with both 'gc' and 'safepoint' will not be logged.)");601out->cr();602603out->print_cr(" -Xlog:disable -Xlog:safepoint=trace:safepointtrace.txt");604out->print_cr("\t Turn off all logging, including warnings and errors,");605out->print_cr("\t and then enable messages tagged with 'safepoint' up to 'trace' level to file 'safepointtrace.txt'.");606607out->print_cr(" -Xlog:async -Xlog:gc=debug:file=gc.log -Xlog:safepoint=trace");608out->print_cr("\t Write logs asynchronously. Enable messages tagged with 'safepoint' up to 'trace' level to stdout ");609out->print_cr("\t and messages tagged with 'gc' up to 'debug' level to file 'gc.log'.");610}611612void LogConfiguration::rotate_all_outputs() {613// Start from index 2 since neither stdout nor stderr can be rotated.614for (size_t idx = 2; idx < _n_outputs; idx++) {615_outputs[idx]->force_rotate();616}617}618619void LogConfiguration::register_update_listener(UpdateListenerFunction cb) {620assert(cb != NULL, "Should not register NULL as listener");621ConfigurationLock cl;622size_t idx = _n_listener_callbacks++;623_listener_callbacks = REALLOC_C_HEAP_ARRAY(UpdateListenerFunction,624_listener_callbacks,625_n_listener_callbacks,626mtLogging);627_listener_callbacks[idx] = cb;628}629630void LogConfiguration::notify_update_listeners() {631assert(ConfigurationLock::current_thread_has_lock(), "notify_update_listeners must be called in ConfigurationLock scope (lock held)");632for (size_t i = 0; i < _n_listener_callbacks; i++) {633_listener_callbacks[i]();634}635}636637bool LogConfiguration::_async_mode = false;638639640