Cette page a été traduite par l'API Cloud Translation.
Switch to English

Écriture

Explique comment écrire une entrée de journal.

Pages de documentation incluant cet exemple de code

Pour afficher l'exemple de code utilisé en contexte, consultez la documentation suivante :

Exemple de code

C#

Pour savoir comment installer et utiliser la bibliothèque cliente pour Logging, consultez la page Bibliothèques clientes Logging.

private void WriteLogEntry(string logId, string message)
{
    var client = LoggingServiceV2Client.Create();
    LogName logName = new LogName(s_projectId, logId);
    LogEntry logEntry = new LogEntry
    {
        LogNameAsLogName = logName,
        Severity = LogSeverity.Info,
        TextPayload = $"{typeof(LoggingSample).FullName} - {message}"
    };
    MonitoredResource resource = new MonitoredResource { Type = "global" };
    IDictionary<string, string> entryLabels = new Dictionary<string, string>
    {
        { "size", "large" },
        { "color", "red" }
    };
    client.WriteLogEntries(logName, resource, entryLabels,
        new[] { logEntry }, _retryAWhile);
    Console.WriteLine($"Created log entry in log-id: {logId}.");
}

Go

Pour savoir comment installer et utiliser la bibliothèque cliente pour Logging, consultez la page Bibliothèques clientes Logging.

const name = "log-example"
logger := client.Logger(name)
defer logger.Flush() // Ensure the entry is written.

infolog := logger.StandardLogger(logging.Info)
infolog.Printf("infolog is a standard Go log.Logger with INFO severity.")

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Logging, consultez la page Bibliothèques clientes Logging.

List<LogEntry> entries = new ArrayList<>();
entries.add(LogEntry.of(StringPayload.of("Entry payload")));
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("key", "value");
entries.add(LogEntry.of(JsonPayload.of(jsonMap)));
logging.write(
    entries,
    WriteOption.logName(logName),
    WriteOption.resource(MonitoredResource.newBuilder("global").build()));

Node.js

Pour savoir comment installer et utiliser la bibliothèque cliente pour Logging, consultez la page Bibliothèques clientes Logging.

// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// Creates a client
const logging = new Logging();

/**
 * TODO(developer): Uncomment the following line to run the code.
 */
// const logName = 'Name of the log to write to, e.g. my-log';

const log = logging.log(logName);

// Modify this resource to match a resource in your project
// See
// https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource
const resource = {
  // This example targets the "global" resource for simplicity
  type: 'global',
};

// A text log entry
const entry = log.entry({resource}, 'Hello, world!');

// A structured log entry
const secondEntry = log.entry(
  {resource: resource},
  {
    name: 'King Arthur',
    quest: 'Find the Holy Grail',
    favorite_color: 'Blue',
  }
);

async function writeLogEntry() {
  // Save the two log entries. You can write entries one at a time, but it is
  // best to write multiple entires together in a batch.
  await log.write([entry, secondEntry]);
  console.log(`Wrote to ${logName}`);
}
writeLogEntry();

PHP

Pour savoir comment installer et utiliser la bibliothèque cliente pour Logging, consultez la page Bibliothèques clientes Logging.

use Google\Cloud\Logging\LoggingClient;

/** Write a log message via the Stackdriver Logging API.
 *
 * @param string $projectId The Google project ID.
 * @param string $loggerName The name of the logger.
 * @param string $message The log message.
 */
function write_log($projectId, $loggerName, $message)
{
    $logging = new LoggingClient(['projectId' => $projectId]);
    $logger = $logging->logger($loggerName, [
        'resource' => [
            'type' => 'gcs_bucket',
            'labels' => [
                'bucket_name' => 'my_bucket'
            ]
        ]
    ]);
    $entry = $logger->entry($message);
    $logger->write($entry);
    printf("Wrote a log to a logger '%s'." . PHP_EOL, $loggerName);
}

Python

Pour savoir comment installer et utiliser la bibliothèque cliente pour Logging, consultez la page Bibliothèques clientes Logging.

def write_entry(logger_name):
    """Writes log entries to the given logger."""
    logging_client = logging.Client()

    # This log can be found in the Cloud Logging console under 'Custom Logs'.
    logger = logging_client.logger(logger_name)

    # Make a simple text log
    logger.log_text("Hello, world!")

    # Simple text log with severity.
    logger.log_text("Goodbye, world!", severity="ERROR")

    # Struct log. The struct can be any JSON-serializable dictionary.
    logger.log_struct(
        {
            "name": "King Arthur",
            "quest": "Find the Holy Grail",
            "favorite_color": "Blue",
        }
    )

    print("Wrote logs to {}.".format(logger.name))

Ruby

Pour savoir comment installer et utiliser la bibliothèque cliente pour Logging, consultez la page Bibliothèques clientes Logging.

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

entry = logging.entry
# payload = "The data you want to log"
entry.payload = payload
# log_name = "The name of the log to write to"
entry.log_name = log_name
entry.severity = :NOTICE
entry.resource.type = "gae_app"
entry.resource.labels[:module_id] = "default"
entry.resource.labels[:version_id] = "20160101t163030"

logging.write_entries entry
puts "Wrote payload: #{entry.payload} to log: #{entry.log_name}"