VictoriaLogs + Promtail Binary Deployment
If you have not rotated MongoDB logs yet, please first read MongoDB Log Rotation.
This deployment option does not include Grafana, so a usable Grafana environment must already be available.
When installing the VictoriaLogs datasource plugin, Grafana must meet the plugin requirements. The current reference VictoriaLogs datasource plugin version is 0.23.5, and Grafana must be >= 10.4.0. If your Grafana version does not meet this requirement, please first refer to Grafana 12.1.2 Upgrade Steps Reference.
Deploy VictoriaLogs
-
Prepare the installation directory
mkdir -p /data/mdtempcd /data/mdtemp -
Download the VictoriaLogs package
wget https://pdpublic.mingdao.com/private-deployment/offline/common/victoria-logs-linux-amd64-v1.43.1.tar.gz -
Extract it to the installation directory
mkdir /usr/local/victorialogs/tar xzvf victoria-logs-linux-amd64-v1.43.1.tar.gz -C /usr/local/victorialogs/ -
Create the data directory
mkdir -p /data/victorialogs -
Write the environment file
cat > /usr/local/victorialogs/victorialogs.env <<'EOF'# VictoriaLogs basic configurationSTORAGE_DATA_PATH=/data/victorialogsHTTP_LISTEN_ADDR=:9428HTTP_AUTH_USERNAME=myuserHTTP_AUTH_PASSWORD=mypassword# Data retention policyRETENTION_PERIOD=30dRETENTION_DISK_USAGE=50GiB# Memory and concurrency controlsMEMORY_ALLOWED_PERCENT=2MAX_CONCURRENT_INSERTS=4MAX_CONCURRENT_REQUESTS=2# Query limitsSEARCH_MAX_QUERY_DURATION=30sSEARCH_MAX_QUERY_TIMERANGE=24hSEARCH_MAX_QUEUE_DURATION=5sSEARCH_LOG_SLOW_QUERY_DURATION=3s# Write protectionINSERT_MAX_LINE_SIZE_BYTES=262144INSERT_MAX_FIELDS_PER_LINE=300# syslog extra fieldsSYSLOG_EXTRA_FIELDS_TCP={"job":"rsyslog"}# Log levelLOGGER_LEVEL=INFOEOFVariable notes:
HTTP_AUTH_USERNAMEandHTTP_AUTH_PASSWORDare used for VictoriaLogs Basic Auth. It is recommended to replace them with a more complex username and password according to your local standards instead of using the example values directly.RETENTION_PERIODis used to set the log retention period. For example,30dmeans logs are retained for 30 days.RETENTION_DISK_USAGEis used to set the disk usage upper limit for VictoriaLogs. For example,50GiBmeans VictoriaLogs can use up to 50 GiB of disk space.- If the log volume is large, it is recommended to tune these two parameters together to prevent disk growth from getting out of control.
-
Write the systemd service file
cat > /etc/systemd/system/victorialogs.service <<'EOF'[Unit]Description=VictoriaLogs Logging ServiceWants=network-online.targetAfter=network-online.target[Service]Type=simpleEnvironmentFile=/usr/local/victorialogs/victorialogs.envEnvironment="GOMEMLIMIT=2GiB"WorkingDirectory=/usr/local/victorialogsExecStart=/usr/local/victorialogs/victoria-logs-prod \-storageDataPath=${STORAGE_DATA_PATH} \-httpListenAddr=${HTTP_LISTEN_ADDR} \-retentionPeriod=${RETENTION_PERIOD} \-retention.maxDiskSpaceUsageBytes=${RETENTION_DISK_USAGE} \-memory.allowedPercent=${MEMORY_ALLOWED_PERCENT} \-maxConcurrentInserts=${MAX_CONCURRENT_INSERTS} \-search.maxConcurrentRequests=${MAX_CONCURRENT_REQUESTS} \-search.maxQueryDuration=${SEARCH_MAX_QUERY_DURATION} \-search.maxQueryTimeRange=${SEARCH_MAX_QUERY_TIMERANGE} \-search.maxQueueDuration=${SEARCH_MAX_QUEUE_DURATION} \-search.logSlowQueryDuration=${SEARCH_LOG_SLOW_QUERY_DURATION} \-insert.maxLineSizeBytes=${INSERT_MAX_LINE_SIZE_BYTES} \-insert.maxFieldsPerLine=${INSERT_MAX_FIELDS_PER_LINE} \-syslog.extraFields.tcp=${SYSLOG_EXTRA_FIELDS_TCP} \-httpAuth.username=${HTTP_AUTH_USERNAME} \-httpAuth.password=${HTTP_AUTH_PASSWORD} \-loggerLevel=${LOGGER_LEVEL}ExecStop=/usr/bin/kill $MAINPIDRestart=on-failureLimitNOFILE=65536TasksMax=2048CPUAccounting=trueCPUQuota=100%MemoryAccounting=trueMemoryMax=2GMemoryLimit=2GMemorySwapMax=0StandardOutput=journalStandardError=journal[Install]WantedBy=multi-user.targetEOF -
Start VictoriaLogs
systemctl daemon-reloadsystemctl enable --now victorialogssystemctl status victorialogs --no-pagerss -lnt | grep '9428'curl -s http://localhost:9428/health
Deploy Promtail
Promtail must be deployed on every MongoDB node. It reads the local mongodb.log file directly and pushes the slow query logs to VictoriaLogs. Each node needs its own Promtail instance so that the log source can be mapped back to the node one by one.
Notes:
PROMTAIL_PUSH_URLmust be changed to the actual VictoriaLogs address.PROMTAIL_USERNAMEandPROMTAIL_PASSWORDmust be changed to the real VictoriaLogs authentication credentials.PROMTAIL_JOB_NAMEmust remain unique on each MongoDB node so that log sources can be distinguished.PROMTAIL_LOG_PATHmust be changed to the absolute path of the MongoDB log file on the current node.- If the log path differs between MongoDB nodes, adjust the corresponding configuration on each node separately.
-
Download Promtail
wget https://pdpublic.mingdao.com/private-deployment/offline/common/promtail-linux-amd64.zip -
Extract and install
mkdir /usr/local/promtail-vlogsunzip promtail-linux-amd64.zip -d /usr/local/promtail-vlogs/ -
Write the configuration file
cat > /usr/local/promtail-vlogs/promtail-config.yaml << 'EOF'server:# Listening porthttp_listen_port: 9081# gRPC server listening port; 0 means randomgrpc_listen_port: 0# gRPC maximum receive message size, default 4 MBgrpc_server_max_recv_msg_size: 4194304# gRPC maximum send message size, default 4 MBgrpc_server_max_send_msg_size: 4194304positions:# File used by Promtail to persist read offsets so collection can continue after restartfilename: /usr/local/promtail-vlogs/positions.yamlclients:- url: "http://10.206.0.5:9428/insert/loki/api/v1/push" # Change this to the VictoriaLogs addressbasic_auth:username: "myuser" # Change this to the VictoriaLogs usernamepassword: "mypassword" # Change this to the VictoriaLogs passwordbatchwait: 1s # Send a batch at most once per secondbatchsize: 102400 # About 100 KBheaders:X-Loki-Disable-Structured-Metadata: "true"scrape_configs:- job_name: mongodbstatic_configs:- targets:- localhostlabels:job: mongodb-01 # Do not reuse this value on every nodehost: ${HOSTNAME}__path__: /data/logs/mongodb/mongodb.log # Absolute path to mongodb.logpipeline_stages:# 1. Parse JSON- json:expressions:ts: t."$date"c: cmsg: msgattr: attr# 2. Use the timestamp from the log itself- timestamp:source: tsformat: RFC3339# Add labels for later match stages- labels:c:msg:# 3. Keep only COMMAND and msg=Slow query logs. During initial deployment, you can comment out these two drop rules for validation.- match:selector: '{c!="COMMAND"}'action: drop- match:selector: '{msg!="Slow query"}'action: drop# 4. Promote fields under attr to the top level for easier LogSQL filtering- json:source: attrexpressions:durationMillis: durationMillisns: nsplanSummary: planSummarydocsExamined: docsExaminedreslen: reslen# 5. Add labels for page display and LogSQL filtering- labels:durationMillis:ns:planSummary:docsExamined:reslen:ts:attr:# 6. Define _msg- template:source: linedestination: linetemplate: >-- {"ns":"{{ .ns }}","durationMillis":"{{ .durationMillis }}","planSummary":"{{ .planSummary }}","docsExamined":"{{ .docsExamined }}","reslen":"{{ .reslen }}","attr":"{{ .attr }}"}- output:source: linelimits_config:readline_rate: 1000000 # Read rate limit: 1 MB/sreadline_burst: 2000000 # Burst read limit: 2 MBEOF -
Write the positions file
cat > /usr/local/promtail-vlogs/positions.yaml << 'EOF'positions: {}EOF -
Write the systemd service file
cat > /etc/systemd/system/promtail-vlogs.service << 'EOF'[Unit]Description=promtail Logging ServiceAfter=network.target[Service]Type=simple# Upper limit for the Go runtime heap; still effective even if cgroup detection failsEnvironment="GOMEMLIMIT=1GiB"ExecStart=/usr/local/promtail-vlogs/promtail-linux-amd64 -config.file=/usr/local/promtail-vlogs/promtail-config.yaml -config.expand-env=trueExecStop=/usr/bin/kill -9 $MAINPIDRestart=on-failure# CPU: hard limit of 1 coreCPUAccounting=trueCPUQuota=100%# Memory: hard limit of 1 GBMemoryAccounting=trueMemoryMax=1GMemoryLimit=1GMemorySwapMax=0LimitNOFILE=65536TasksMax=1024[Install]WantedBy=multi-user.targetEOF -
Start Promtail
systemctl daemon-reloadsystemctl enable --now promtail-vlogssleep 1ss -lnt | grep '9081'curl -s http://127.0.0.1:9081/ready# Check whether data is being pushedcurl -s http://127.0.0.1:9081/metrics | egrep -i 'promtail_.*(client|sent|dropped|error|retry|targets)' | head -n 80
Grafana Configuration
This deployment option does not include Grafana. If Grafana is not available in your environment yet, please finish installing or upgrading Grafana first before continuing. The current reference VictoriaLogs datasource plugin version is
0.23.5, and Grafana must be>= 10.4.0. If your Grafana version does not meet this requirement, please first refer to Grafana 12.1.2 Upgrade Steps Reference.
-
Install the VictoriaLogs datasource plugin
cd /data/mdtemp# Grafana >= 10.4.0; if not, upgrade Grafana firstwget https://pdpublic.mingdao.com/private-deployment/offline/common/victoriametrics-logs-datasource-v1.43.1_DATASOURCE.tar.gztar xzvf victoriametrics-logs-datasource-v1.43.1_DATASOURCE.tar.gz -C /usr/local/grafana/data/plugins/systemctl restart grafana -
Configure the datasource
- Set
urlto the VictoriaLogs address, for examplehttp://127.0.0.1:9428. - Turn on
Basic auth. - Set
UsertoHTTP_AUTH_USERNAME. - Set
PasswordtoHTTP_AUTH_PASSWORD. - Keep
Maximum linesat2000000.
- Set
-
Import the slow query dashboard
This dashboard file is ready to use. Download it and import it into Grafana directly. If your environment already has its own dashboard version, you can also use it as a reference and make further adjustments.
Download or open the dashboard JSON
- Dashboard file:
mongodb-VictoriaLogs-Slow-Query.en.json - Import method: click
Import dashboardin Grafana, then upload this file - After importing, make sure the correct VictoriaLogs datasource is selected
- If you want to inspect the content first, you can also open the JSON file directly in your browser
Open the JSON file in a browser - Dashboard file: