Let's look deeper how all this works:
There is a number of sensors that provide the ECM with all necessary inputs such as the engine temperature, ambient temperature, vehicle speed, load, etc. According to these inputs, the ECM makes initial adjustments adding or subtracting fuel, advancing or retarding the ignition timing, increasing or decreasing idle speed, etc.
There is a primary (upstream) oxygen sensor installed in the exhaust before catalytic converter that monitors the quality of combustion in the cylinders. Based on the feedback from this oxygen sensor the ECM makes further adjustments to the air-fuel mixture to reduce emissions.
There is another, secondary (downstream) oxygen sensor installed after catalytic converter in the exhaust that monitors catalytic converter's efficiency.
Besides, there are few additional vehicle systems related to the emission control. For example, there is an Evaporative system (EVAP), that prevents gasoline vapors inside the gas tank from escaping into the atmosphere. The EVAP system also contains a number of sensors and actuators controlled by the ECM.
The computer or ECM constantly tests operation of all sensors and components. When any of the sensor signals is missing or out of normal range, the ECM sets a fault and illuminates the "Check Engine" or "Service Engine Soon" light also called MIL (Malfunction Indication Light) storing the corresponding Diagnostic Trouble Code (DTC) in the ECM memory.
The same happens if a mechanical component of controlled system fails. For example, mechanical problem inside the transmission also can turn the "check engine" light on. Even not properly closed gas cap will cause the "check engine" light to come on - the ECM constantly checks if the gas tank is sealed properly.
To sum up, when the "Check Engine" or "Service Engine Soon" light comes on and stays on, there is a problem with your vehicle. This could be a problem with the engine, transmission, or some emission-related component or system.
The stored trouble code can be retrieved with the special scan tool by the technician. The code itself does not tell exactly which part to replace, it only gives a direction where to look for - the technician has to perform certain tests specific for each code to find the exact cause of the problem.