S7-1200/S7-1500 Data Log: Automating CSV Download and Deletion

David Krause17 min read
S7-1200SiemensTutorial / How-to
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

S7-1200/S7-1500 Data Log: Automating CSV Download and Deletion

Generating a daily CSV data log on a SIMATIC S7-1200 or S7-1500 is straightforward: drop the standard DataLogCreate, DataLogOpen, DataLogWrite, and DataLogClose instructions into the user program and the CPU writes a comma-separated file to the load memory or SIMATIC memory card. The hard part is the second half of the workflow — pulling that file off the PLC on schedule, archiving it on the engineering or customer PC, and then deleting it from the SD card so the next day starts with a clean file. Customers who require "one CSV per day, no manual intervention, and no permanent storage on the PLC" push this problem straight onto the automation engineer.

This reference covers the full loop: how to expose the data log files through the integrated web server, what the direct-file URL looks like on S7-1200 vs. S7-1500, why the link that works for an S7-1200 silently returns 404 on an S7-1500, how to script the download with PowerShell, Python or curl, how to deal with HTTPS-only web servers, and the available methods for deleting the log from the PC side without a programming device on the bench. The two background pain points raised in the original forum thread — the missing DataLogDelete instruction in TIA Portal V11 SP2 and the S7-1500 direct-link mismatch — are treated explicitly.

Scope note. The procedure assumes the PLC is on a closed OT/IT network or a properly segmented VLAN. The web server on a SIMATIC CPU is not a hardened file server; treat the data log path as read-only and never expose the CPU directly to the Internet.

1. Data Logging Architecture on S7-1200 and S7-1500

Both CPU families store the data log as a regular file inside the CPU's load memory (internal flash) or, more commonly, on the SIMATIC memory card plugged into the front of the CPU. The runtime library “Data log” contains the instruction set used to manage the file. A typical S7-1200 application uses these instructions in this order:

  1. DataLogCreate — creates the CSV on first power-up with a fixed name and column header.
  2. DataLogOpen — opens the file for appending (idempotent; re-opens if the CPU reboots).
  3. DataLogWrite — appends one record per scan or per event.
  4. DataLogClose — closes the file; the file is still present on the SD card.
  5. DataLogNewFile — closes the current log and opens a new one with an incremented name (used to roll per-day files).

The CPU exposes these files through its integrated web server. With web server "activated" and a user with the read files permission, the standard web page at http://<cpu-ip> already includes a “File browser” link that lists everything under the data log directory. The link is fine for engineers sitting in front of a PG; it is not fine for an unattended script that must run on a customer server.

2. Prerequisites — Web Server, Users, and the SD Card

Before any download or delete script can run, the CPU must be configured correctly. The following checklist assumes TIA Portal V16 or later; older projects are compatible but the navigation may differ.

  1. Enable the web server. In the device configuration of the CPU, open “Web server” and tick “Activate web server on this module”. Note that S7-1200 firmware V4.0 introduced the user-defined web pages; older firmware (V1–V3) is the typical target for the direct-file URL approach used in this article.
  2. Define a user with read-files rights. In the same dialog, “User management” → add a user, assign the Read files permission, and set a strong password. The script will authenticate as this user.
  3. Insert and format a SIMATIC memory card. Use a Siemens SMC (6ES7954-8LF02-0AA0, 4 MB, or 6ES7954-8LE03-0AA0, 12 MB) for S7-1200; for S7-1500 use a 2 MB or larger SIMATIC SD card (e.g. 6ES7954-8LP02-0AA0, 32 MB). Format the card from the CPU's online & diagnostics view if the PLC is replacing an existing one; the CPU will create a standard FAT file system that is readable by a Windows PC when the card is pulled.
  4. Decide the storage location. By default DataLogCreate writes to the memory card; this is what you want for long retention. Writing to internal load memory is faster but the file system is not Windows-readable when the card is removed.
  5. Roll the file per day. Use a cyclic OB (e.g. OB1) bit triggered by a daily RTC compare, or call DataLogNewFile from a time-of-day interrupt OB (OB10 on S7-1200 / S7-1500) so each calendar day produces its own CSV with a date-coded file name such as LOG_2025-03-12.csv.
HTTPS versus HTTP. If the “Permit access only with HTTPS” option is checked in the web server properties, plain HTTP requests will be refused. Section 6 below covers how to script around HTTPS without weakening the CPU configuration.

3. Direct File URL — S7-1200 vs. S7-1500

The web server on the S7-1200 serves files from a flat hierarchy rooted at the memory card's /DataLog/ folder. The browser shows links of the form:

http://192.168.0.10/DataLog/LOG_2025-03-12.csv

The S7-1500 web server is implemented on top of the standard “SIMATIC Automation Center” pages, not the legacy S7-1200 file browser. The same file path returns HTTP 404 Not Found on a 1500 because the URL namespace is different. The S7-1500 exposes its data log through the file browser portal page rather than the flat /DataLog/ path. Two workable approaches are:

  • Use the file-browser portal page. Authenticate, request the portal page, parse the form, and follow the link that the page returns for the file. This is fragile because the page layout is subject to firmware changes, but it works on every S7-1500 firmware from V1.8 through V2.9.
  • Read the file from the SD card directly. S7-1500 does not natively support a flat /DataLog/ URL, so the cleanest “download” is to pull the SD card, copy the file, and reinsert. In practice most plants automate around this by mounting the SD card via a network share, or by using a separate S7-1500 webserver file called through user-defined web pages.

For the rest of this article the URL examples use the S7-1200 form. For S7-1500 replace the GET path with the form the portal returns, and keep the same authentication, retry, and HTTPS logic.

4. The Data Log Instruction Set in TIA Portal

The five data-log instructions documented in the TIA Portal help are part of the “Data log” library and are available in every S7-1200/S7-1500 firmware from V1.0 onward. Their function block numbers and behaviour are stable across TIA Portal versions, but the available set has changed over time:

Instruction FB number Available since Purpose
DataLogCreate FB 190 TIA Portal V11 Create the CSV file with a defined header row.
DataLogOpen FB 191 TIA Portal V11 Open an existing log for appending.
DataLogWrite FB 192 TIA Portal V11 Append a record.
DataLogClose FB 193 TIA Portal V11 Close the log so the OS flushes the buffer.
DataLogNewFile FB 194 TIA Portal V11 Close the current log and open a new one with the same columns.
DataLogDelete FB 195 TIA Portal V14 SP1 (see note) Delete a closed log file by name.
About DataLogDelete. The original post mentions that “DataLogDelete should be included in TIA Portal V11 SP2.” In practice the instruction was not shipped with V11 SP2 and was added in a later Service Pack. The first TIA Portal version that exposes DataLogDelete in the instruction catalog is V14 SP1; engineers on older projects should verify against the TIA Portal help for their installed version. If DataLogDelete is not present, the deletion has to be done either by the script on the PC side over the web server (where supported) or by resetting / reformatting the SD card.

A minimal “create on first run, open every cycle, write, close on day change” SCL block looks like this:

// SCL - S7-1200/1500 data log lifecycle
IF "FirstScan" THEN
    DataLogCreate_Instance(REQ := TRUE,
                           DONE => "DLG_done",
                           BUSY => "DLG_busy",
                           ERROR => "DLG_err",
                           STATUS => "DLG_status",
                           NAME := 'LOG',
                           ID => "DLG_id",
                           FORMAT := 0,
                           HEADER := 'Date,Time,Tag1,Tag2');
    "FirstScan" := FALSE;
END_IF;

DataLogOpen_Instance(REQ := "DLG_id" = 0,
                     NAME := 'LOG',
                     ID => "DLG_id");

DataLogWrite_Instance(REQ := "WriteTrigger",
                      ID := "DLG_id",
                      FORMAT := 0,
                      DATA := "LogRow");

// OB10 - roll a new file at midnight
IF "MidnightPulse" THEN
    DataLogNewFile_Instance(REQ := TRUE,
                            ID := "DLG_id",
                            NAME := 'LOG');
END_IF;

5. Automating the Download from a PC

Once the direct URL is known, the download is a single authenticated HTTP GET. The three practical environments on the customer side are Windows PowerShell, Python, and Linux curl / wget. All three support HTTPS, basic authentication, and a configurable destination folder.

5.1 PowerShell (recommended for Windows servers)

# Download-Datalog.ps1
param(
    [string]$CpuIp   = '192.168.0.10',
    [string]$User    = 'datalog',
    [string]$Pass    = 'ChangeMe!',
    [string]$Remote  = '/DataLog/LOG_2025-03-12.csv',
    [string]$Local   = 'D:\Archive\LOG_2025-03-12.csv'
)

$sec = ConvertTo-SecureString $Pass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($User, $sec)

# Pair the secure string with the PSCredential; this is the canonical .NET path.
$pair  = "${User}:${Pass}"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($pair)
$basic = 'Basic ' + [Convert]::ToBase64String($bytes)

$url = "http://$CpuIp$Remote"
try {
    Invoke-WebRequest -Uri $url -Headers @{ Authorization = $basic } -OutFile $Local -TimeoutSec 30
    Write-Host "Downloaded $Remote -> $Local"
} catch {
    Write-Error "Download failed: $_"
    exit 2
}

Schedule the script with Windows Task Scheduler at, for example, 23:55 every day, and you have a fully unattended collector.

5.2 Python (cross-platform)

#!/usr/bin/env python3
import argparse, datetime, pathlib, requests

p = argparse.ArgumentParser()
p.add_argument('--cpu',    default='192.168.0.10')
p.add_argument('--user',   required=True)
p.add_argument('--token',  required=True, help='Web-server password')
p.add_argument('--remote', default='/DataLog/LOG.csv')
p.add_argument('--outdir', default='./archive')
args = p.parse_args()

today = datetime.date.today().isoformat()
remote = args.remote.replace('LOG.csv', f'LOG_{today}.csv')
local  = pathlib.Path(args.outdir) / pathlib.Path(remote).name
local.parent.mkdir(parents=True, exist_ok=True)

url = f'http://{args.cpu}{remote}'
r = requests.get(url, auth=(args.user, args.token), timeout=30, verify=False)
r.raise_for_status()
local.write_bytes(r.content)
print(f'OK {remote} -> {local}  ({len(r.content)} bytes)')

Drop the verify=False flag when a proper CA-signed certificate is installed on the CPU. The requests library will otherwise fail with SSLCertVerificationError.

5.3 curl / wget on Linux

#!/bin/bash
set -euo pipefail
CPU="192.168.0.10"
USER="datalog"
PASS="ChangeMe!"
TODAY="$(date +%F)"
REMOTE="/DataLog/LOG_${TODAY}.csv"
LOCAL="/srv/archive/LOG_${TODAY}.csv"

# -k trusts self-signed certs (HTTPS only)
curl -fsSL -u "${USER}:${PASS}" -o "${LOCAL}" "http://${CPU}${REMOTE}"

6. HTTPS-Only Web Server — Workarounds

  1. Install the CPU certificate as trusted on the script host. Export the certificate from the CPU's web-server properties (TIA Portal → CPU → Web server → Certificate) and import it into the Windows “Trusted Root Certification Authorities” store or the Linux /usr/local/share/ca-certificates/ directory. This is the only “production-clean” option; the connection is encrypted, the CPU is authenticated, and the script can use plain https:// URLs.
  2. Accept self-signed certs in the script. For prototyping only: PowerShell Invoke-WebRequest -SkipCertificateCheck, curl -k, Python requests.get(..., verify=False). Do not use this in a production environment where the script host is shared.
  3. Front the CPU with a reverse proxy. Put nginx, traefik, or a Windows IIS with Application Request Routing in front of the CPU. The proxy terminates TLS with a real certificate, the script talks to the proxy over plain HTTP on localhost, and the CPU keeps its own HTTPS configuration. This is the cleanest answer for plants that already have a proxy in place.
  4. Disable HTTPS for the file-browser path only. Not possible on a SIMATIC CPU — the setting is global. Either the whole web server is HTTPS or none of it is.

7. Automating Deletion of Closed Data Logs

Deletion is the part of the workflow that the original post could not solve. The options, ordered from cleanest to most invasive, are as follows.

7.1 Use DataLogDelete on the PLC side

From TIA Portal V14 SP1 onward, the DataLogDelete instruction is available in the catalog under “Extended instructions → Data log”. Wire it to a daily trigger so that yesterday's closed file is erased after the download script has confirmed it has the local copy.

// Delete yesterday's log after the PC confirms download
IF "PC_Ack" THEN
    DataLogDelete_Instance(REQ := TRUE,
                           DONE => "DL_del_done",
                           BUSY => "DL_del_busy",
                           ERROR => "DL_del_err",
                           STATUS => "DL_del_status",
                           NAME := 'LOG_2025-03-12');
    "PC_Ack" := FALSE;
END_IF;
Sync hazard. The PC script and the PLC need a handshake bit, e.g. a flag in the bit memory area that the script sets over the same web-server interface (via a user-defined web page) once the file is on disk. Delete on the PLC only after this bit is true, otherwise the next day's start will run without a record of yesterday.

7.2 Delete through the web server's file browser

Some Siemens firmware versions (S7-1200 V4.4 and later, S7-1500 V2.6 and later) expose a “Delete” button next to each file in the file browser portal. A scripted solution is possible by POST-ing to the portal's form action, but the form's hidden fields change with firmware. The most robust way to drive this from a script is to use a headless browser such as Playwright or Selenium:

# Playwright snippet - delete all LOG_*.csv files
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('https://192.168.0.10/Portal/Portal.mwsl')
    page.fill('#username', 'datalog')
    page.fill('#password', 'ChangeMe!')
    page.click('#submit')
    # Click the trash icon next to each data log file
    for row in page.query_selector_all('tr.datalog-row'):
        row.query_selector('button.delete').click()
        page.on('dialog', lambda d: d.accept())
    browser.close()

This is slow and CPU-firmware-dependent; prefer DataLogDelete on the PLC if the TIA Portal version allows it.

7.3 Pull the SD card and re-insert

For plants where the PLC is physically accessible, the most reliable deletion is the most low-tech: a service technician pulls the card, copies the day's file to a Windows PC, and re-inserts. To script this, mount the SD card via a USB card reader on the PC and run a robocopy + del pair, then return the card. Not appropriate for unattended 24/7 plants, but acceptable in laboratory or test-rig environments.

7.4 “Reset to factory settings” (legacy workaround)

The original post notes that “deleting is possible by giving a reset to factory settings.” This wipes the entire project, not just the data log, so it is not an acceptable daily routine. Mention it only for completeness.

8. HMI-Based Alternative When a Script Is Not Acceptable

When the OT network policy forbids any external process from authenticating against the CPU, a SIMATIC HMI panel (Comfort or Unified) can run the same workflow natively. Configure the HMI as follows:

  1. Add a logging tag with a file-based data log on a network share mounted on the HMI's Windows CE / Win IoT partition.
  2. Set the log to “cyclic” with a daily segment change — the HMI's log will produce exactly one CSV per day, archived to the share.
  3. Disable the PLC-side data log instructions to avoid duplicate files.

Pro: no PC-side scripting required, the panel is already on the OT network. Con: the log no longer lives on the PLC, which is sometimes a regulatory requirement, and the panel must be a Comfort or Unified line (Basic panels do not support file logging).

9. SD Card Lifecycle and File-System Considerations

A few constraints that surface only after the system has been running for several months.

  • File-system wear. The data log writes a new record for every DataLogWrite call. On a high-frequency process this can saturate the SD card's write endurance. A typical 4 MB Siemens SMC is rated for 100 000 write cycles per sector; on a 1 Hz log this is ~28 hours of continuous writing. Roll the log file before the file system runs out of contiguous sectors, and consider a high-endurance card (e.g. 6ES7954-8LP01-0AA0).
  • Maximum number of open files. The CPU holds at most 10 simultaneously open data log files. If you forget to DataLogClose a daily file, the next day's DataLogCreate will return status word 80A7 “no resource available”.
  • Time stamping. DataLogWrite with FORMAT = 1 prepends a CPU timestamp. Use this when the PC needs to know the exact moment the row was written — relying on the filename's date is not safe if the PLC clock drifts.
  • Power loss. On an S7-1200 the file is buffered to internal flash every few seconds; on an S7-1500 the data log goes to the SD card and is buffered in main memory until the OS flushes. Plan for up to 64 KB of data loss on a hard power cycle.

10. Verification & Troubleshooting Matrix

Use this matrix to map the symptom seen in production to the most likely cause and the corrective action.

Symptom Likely cause Action
Script returns HTTP 401 Unauthorized User missing "read files" right, or wrong password. Re-check user management on the CPU. Confirm the script base-64 encodes user:pass.
Script returns HTTP 404 on S7-1500 Wrong URL namespace; S7-1500 does not expose /DataLog/.... Replace the GET path with the file-browser portal page URL, or move the file via the SD card.
Download works once, fails the next day SD card full because deletion never runs. Enable DataLogDelete (TIA V14 SP1+), or have the script call a user-defined web page that triggers deletion.
PowerShell reports "The request was aborted: Could not create SSL/TLS secure channel" PowerShell is on .NET Framework 4.5 which defaults to TLS 1.0; CPU requires TLS 1.2. Add [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 at the top of the script.
Python requests raises SSLCertVerificationError Self-signed CPU certificate not trusted on the script host. Import the CPU certificate into the host trust store, or set verify=False for prototyping only.
Status word 80A7 on DataLogCreate More than 10 data log files open simultaneously. Audit the program for missing DataLogClose calls; close files at the end of each day.
Status word 80B1 on DataLogWrite ID is invalid because the file was re-created at midnight and the OB1 still holds the old handle. Refresh the ID by calling DataLogOpen on a rising edge of "new day".
Browser shows the file, but the direct GET returns 403 HTTPS-only web server setting is on, the script is using http://. Use https:// in the script, or front the CPU with a reverse proxy.

11. Sample End-to-End Daily Workflow

Putting all of the above together, the daily routine of an unattended PC is:

  1. 23:55 — PC cron / Task Scheduler triggers the download script. The script computes today's filename (LOG_YYYY-MM-DD.csv), GETs it from the CPU, and writes it to D:\Archive\.
  2. 23:57 — Script verifies the local file size is > 0 and the line count matches the expected header. If yes, the script POSTs to a user-defined web page on the CPU, setting a tag named PC_Ack.
  3. 23:59 — PLC's DataLogNewFile rolls today's log into tomorrow's slot (or, depending on naming strategy, tomorrow's OB10 starts a fresh file).
  4. 00:00 — PLC's DataLogDelete runs, removing yesterday's CSV. SD card space is freed.
  5. 00:05 — Audit log on the PC: a JSON line with the timestamp, filename, byte count, and SHA-256 of the file is appended to audit.log for the customer's compliance trail.

What is the direct URL to download a data log file from an S7-1200?

The standard form is http://<cpu-ip>/DataLog/<filename>.csv, served with HTTP basic authentication as a user that has the “read files” permission in the CPU's web-server user management. On S7-1500 this path returns 404; use the file-browser portal page or the user-defined web pages instead.

Which TIA Portal version first shipped the DataLogDelete instruction?

The DataLogDelete instruction is not present in TIA Portal V11 SP2. It was added in a later Service Pack — typically TIA Portal V14 SP1 or newer. Verify against the TIA Portal help of the installed version; if the instruction is missing, delete the file through the PLC's web interface or by removing the SD card.

How do I download files from a CPU whose web server is set to HTTPS only?

Use an https:// URL in the script, ensure the host trusts the CPU's certificate (or call verify=False in Python, -k in curl, -SkipCertificateCheck in PowerShell for prototyping). For TLS 1.2 enforcement on Windows PowerShell, set [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 before the request.

Why does the S7-1200 download link return 404 on the S7-1500?

The S7-1500 web server is implemented on top of the SIMATIC Automation Center portal pages rather than the S7-1200's flat file browser. The data log files are exposed through the portal page's links, not under a /DataLog/ path. Either follow the form link the portal returns, or use the user-defined web pages feature to expose the file at a stable URL.

Can I avoid writing a download script by using an HMI panel?

Yes. Configure a SIMATIC Comfort or Unified HMI to log to a network share with a daily segment change. The panel produces one CSV per day on the share without any PC-side code. The trade-off is that the data is no longer on the PLC, which may conflict with customer data-residency requirements, and the panel must be a Comfort or Unified line — Basic panels do not support file logging.

What SD card size should I use for a daily log on an S7-1200?

For one CSV per day with a few hundred kilobytes of data, a 4 MB Siemens SMC (6ES7954-8LF02-0AA0) is sufficient. For long retention without daily deletion, or for high-frequency logs, use a 12 MB (6ES7954-8LE03-0AA0) or larger card. For S7-1500, use a SIMATIC SD card (e.g. 6ES7954-8LP02-0AA0, 32 MB) to ensure correct formatting and write-endurance specifications.

Back to blog